id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_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))) {
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.
}
p += chunksize;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_463_0 |
crossvul-cpp_data_good_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;
if( *p >= max - 2) {
zend_error(E_WARNING, "Bad unserialize data");
return -1;
}
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 -1;
}
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 501 "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 875 "ext/standard/var_unserializer.re"
{ return 0; }
#line 563 "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 869 "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 612 "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 717 "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 (elements < 0) {
efree(class_name);
return 0;
}
if (incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 795 "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 704 "ext/standard/var_unserializer.re"
{
long elements;
if (!var_hash) return 0;
INIT_PZVAL(*rval);
elements = object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR);
if (elements < 0) {
return 0;
}
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 833 "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 683 "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 875 "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 648 "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 931 "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 615 "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 985 "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 605 "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 1083 "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 590 "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 1157 "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 563 "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 1211 "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 556 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_BOOL(*rval, parse_iv(start + 2));
return 1;
}
#line 1226 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 549 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_NULL(*rval);
return 1;
}
#line 1236 "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 526 "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 1282 "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 505 "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 1326 "ext/standard/var_unserializer.c"
}
#line 877 "ext/standard/var_unserializer.re"
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4825_1 |
crossvul-cpp_data_good_351_4 | /*
* card-coolkey.c: Support for Coolkey
*
* Copyright (C) 2001, 2002 Juha Yrjölä <juha.yrjola@iki.fi>
* Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
* Copyright (C) 2016, Red Hat, Inc.
*
* Coolkey driver author: Robert Relyea <rrelyea@redhat.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
#include <sys/types.h>
#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
#include "iso7816.h"
#include "gp.h"
#include "../pkcs11/pkcs11.h"
#define COOLKEY_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */
/*
* COOLKEY hardware and APDU constants
*/
#define COOLKEY_MAX_CHUNK_SIZE 240 /* must be less than 255-8 */
/* ISO 7816 CLA values used by COOLKEY */
#define ISO7816_CLASS 0x00
#define GLOBAL_PLATFORM_CLASS 0x80
#define COOLKEY_CLASS 0xb0
/* ISO 71816 INS values used by COOLKEY */
#define ISO7816_INS_SELECT_FILE 0xa4
#define ISO7816_INS_GET_DATA 0xca
/* COOLKEY specific INS values (public) */
#define COOLKEY_INS_GET_LIFE_CYCLE 0xf2
#define COOLKEY_INS_GET_STATUS 0x3c
#define COOLKEY_INS_VERIFY_PIN 0x42
#define COOLKEY_INS_LIST_OBJECTS 0x58
/* COOLKEY specific INS values (require nonce) */
#define COOLKEY_INS_COMPUTE_CRYPT 0x36
#define COOLKEY_INS_COMPUTE_ECC_KEY_AGREEMENT 0x37
#define COOLKEY_INS_COMPUTE_ECC_SIGNATURE 0x38
#define COOLKEY_INS_GET_RANDOM 0x72
#define COOLKEY_INS_READ_OBJECT 0x56
#define COOLKEY_INS_WRITE_OBJECT 0x54
#define COOLKEY_INS_LOGOUT 0x61
/* COMPUTE_CRYPT and COMPUT_ECC parameters */
#define COOLKEY_CRYPT_INIT 1
#define COOLKEY_CRYPT_PROCESS 2
#define COOLKEY_CRYPT_FINAL 3
#define COOLKEY_CRYPT_ONE_STEP 4
#define COOLKEY_CRYPT_MODE_RSA_NO_PAD 0x00
#define COOLKEY_CRYPT_LOCATION_APDU 0x01
#define COOLKEY_CRYPT_LOCATION_DL_OBJECT 0x02
#define COOLKEY_CRYPT_DIRECTION_ENCRYPT 0x03
/* List Objects parameters */
#define COOLKEY_LIST_RESET 0x00
#define COOLKEY_LIST_NEXT 0x01
/* Special object identifiers */
#define COOLKEY_DL_OBJECT_ID 0xffffffff
#define COOLKEY_COMBINED_OBJECT_ID 0x7a300000 /* 'z0\0\0' */
#define COOLKEY_INVALID_KEY 0xff00
#define COOLKEY_KEY_CLASS 'k'
#define COOLKEY_NONCE_SIZE 8
/* returned from the coolkey extended life cycle apdu */
typedef struct coolkey_life_cycle {
u8 life_cycle;
u8 pin_count;
u8 protocol_version_major;
u8 protocol_version_minor;
} coolkey_life_cycle_t;
/* return by the coolkey status apdu */
typedef struct coolkey_status {
u8 protocol_version_major;
u8 protocol_version_minor;
u8 applet_major_version;
u8 applet_minor_version;
u8 total_object_memory[4];
u8 free_object_memory[4];
u8 pin_count;
u8 key_count;
u8 logged_in_identities[2];
} coolkey_status_t;
/* returned by the iso get status apdu with the global platform cplc data parameters */
typedef struct global_platform_cplc_data {
u8 tag[2];
u8 length;
u8 ic_fabricator[2];
u8 ic_type[2];
u8 os_id[2];
u8 os_date[2];
u8 os_level[2];
u8 fabrication_data[2];
u8 ic_serial_number[4];
u8 ic_batch[2];
u8 module_fabricator[2];
u8 packing_data[2];
u8 icc_manufacturer[2];
u8 ic_embedding_data[2];
u8 pre_personalizer[2];
u8 ic_pre_personalization_data[2];
u8 ic_pre_personalization_id[4];
u8 ic_personalizaer[2];
u8 ic_personalization_data[2];
u8 ic_personalization_id[4];
} global_platform_cplc_data_t;
/* format of the coolkey_cuid, either constructed from cplc data or read from the combined object */
typedef struct coolkey_cuid {
u8 ic_fabricator[2];
u8 ic_type[2];
u8 ic_batch[2];
u8 ic_serial_number[4];
} coolkey_cuid_t;
/* parameter for list objects apdu */
typedef struct coolkey_object_info {
u8 object_id[4];
u8 object_length[4];
u8 read_acl[2];
u8 write_acl[2];
u8 delete_acl[2];
} coolkey_object_info_t;
/* parameter for the read object apdu */
typedef struct coolkey_read_object_param {
u8 object_id[4];
u8 offset[4];
u8 length;
} coolkey_read_object_param_t;
/* parameter for the write object apdu */
typedef struct coolkey_write_object_param {
coolkey_read_object_param_t head;
u8 buf[COOLKEY_MAX_CHUNK_SIZE];
} coolkey_write_object_param_t;
/* coolkey uses muscle like objects, but when coolkey is managed by the TPS system
* it creates a single object and encodes the individual objects inside the
* common single object. This allows more efficient reading of all the objects
* (because we can use a single apdu call and we can compress all the objects
* together and take advantage of the fact that many of the certs share the same subject and issue). */
typedef struct coolkey_combined_header {
u8 format_version[2];
u8 object_version[2];
coolkey_cuid_t cuid;
u8 compression_type[2];
u8 compression_length[2];
u8 compression_offset[2];
} coolkey_combined_header_t;
#define COOLKEY_COMPRESSION_NONE 0
#define COOLKEY_COMPRESSION_ZLIB 1
/*
* This is the header of the decompressed portion of the combined object
*/
typedef struct coolkey_decompressed_header {
u8 object_offset[2];
u8 object_count[2];
u8 token_name_length;
u8 token_name[255]; /* arbitrary size up to token_name_length */
} coolkey_decompressed_header_t;
/*
* header for an object. There are 2 types of object headers, v1 and v0.
* v1 is the most common, and is always found in a combined object, so
* we only specify the v0 in the name of the structure.
*/
typedef struct coolkey_v0_object_header {
u8 record_type; /* version 0 or version 1 */
u8 object_id[4]; /* coolkey object id */
u8 attribute_data_len[2]; /* the length in bytes of the next block of
* attribute records */
/* followed by the first attribute record */
} coolkey_v0_object_header_t;
typedef struct coolkey_v0_attribute_header {
u8 attribute_attr_type[4]; /* CKA_ATTRIBUTE_TYPE */
u8 attribute_data_len[2]; /* Length of the attribute */
/* followed by the actual attribute data */
} coolkey_v0_attribute_header_t;
/* combined objects are v1 objects without the record_type indicator */
typedef struct coolkey_combined_object_header {
u8 object_id[4]; /* coolkey object id */
u8 fixed_attributes_values[4]; /* compressed fixed attributes */
u8 attribute_count[2]; /* the number of attribute records that follow */
/* followed by the first attribute */
} coolkey_combined_object_header_t;
typedef struct coolkey_object_header {
u8 record_type; /* version 0 or version 1 */
u8 object_id[4]; /* coolkey object id */
u8 fixed_attributes_values[4]; /* compressed fixed attributes */
u8 attribute_count[2]; /* the number of attribute records that follow */
/* followed by the first attribute */
} coolkey_object_header_t;
#define COOLKEY_V0_OBJECT 0
#define COOLKEY_V1_OBJECT 1
/* vi attribute header */
typedef struct coolkey_attribute_header {
u8 attribute_attr_type[4]; /* CKA_ATTRIBUTE_TYPE */
u8 attribute_data_type; /* the Type of data stored */
/* optional attribute data, or attribute len+data, depending on the value of data_type */
} coolkey_attribute_header_t;
/* values for attribute_data_type */
#define COOLKEY_ATTR_TYPE_STRING 0
#define COOLKEY_ATTR_TYPE_INTEGER 1
#define COOLKEY_ATTR_TYPE_BOOL_FALSE 2
#define COOLKEY_ATTR_TYPE_BOOL_TRUE 3
/*
* format of the fix_attribute values. These are stored as a big endian uint32_t with the below bit field
* Definitions:
*
struct coolkey_fixed_attributes_values {
uint32_t cka_id:4;
uint32_t cka_class:3;
uint32_t cka_token:1;
uint32_t cka_private:1;
uint32_t cka_modifiable:1;
uint32_t cka_derive:1;
uint32_t cka_local:1;
uint32_t cka_encrypt:1;
uint32_t cka_decrypt:1;
uint32_t cka_wrap:1;
uint32_t cka_unwrap:1;
uint32_t cka_sign:1;
uint32_t cka_sign_recover:1;
uint32_t cka_verify:1;
uint32_t cka_verify_recover:1;
uint32_t cka_sensitive:1;
uint32_t cka_always_sensitive:1;
uint32_t cka_extractable:1;
uint32_t cka_never_extractable:1;
uint32_t reserved:8;
};
* cka_class is used to determine which booleans are valid. Any attributes in the full attribute list
* takes precedence over the fixed attributes. That is if there is a CKA_ID in the full attribute list,
* The cka_id in the fixed_attributes is ignored. When determining which boolean attribute is valid, the
* cka_class in the fixed attributes are used, even if it is overridden by the full attribute list.
* valid cka_class values and their corresponding valid bools are as follows:
*
* 0 CKO_DATA cka_private, cka_modifiable, cka_token
* 1 CKO_CERTIFICATE cka_private, cka_modifiable, cka_token
* 2 CKO_PUBLIC_KEY cka_private, cka_modifiable, cka_token
* cka_derive, cka_local, cka_encrypt, cka_wrap
* cka_verify, cka_verify_recover
* 3 CKO_PRIVATE_KEY cka_private, cka_modifiable, cka_token
* cka_derive, cka_local, cka_decrypt, cka_unwrap
* cka_sign, cka_sign_recover, cka_sensitive,
* cka_always_sensitive, cka_extractable,
* cka_never_extractable
* 4 CKO_SECRET_KEY cka_private, cka_modifiable, cka_token
* cka_derive, cka_local, cka_encrypt, cka_decrypt,
* cka_wrap, cka_unwrap, cka_sign, cka_verify,
* cka_sensitive, cka_always_sensitive,
* cka_extractable, cka_never_extractable
* 5-7 RESERVED none
*
*/
/*
* Coolkey attribute record handling functions.
*/
/* get the length of the attribute from a V1 attribute header. If encoded_len == true, then return the length of
* the attribute data field (including any explicit length values, If encoded_len = false return the length of
* the actual attribute data.
*/
static int
coolkey_v1_get_attribute_len(const u8 *attr, size_t buf_len, size_t *len, int encoded_len)
{
coolkey_attribute_header_t *attribute_head = (coolkey_attribute_header_t *)attr;
*len = 0;
/* don't reference beyond our buffer */
if (buf_len < sizeof(coolkey_attribute_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
switch (attribute_head->attribute_data_type) {
case COOLKEY_ATTR_TYPE_STRING:
if (buf_len < (sizeof(coolkey_attribute_header_t) +2)) {
break;
}
*len = bebytes2ushort(attr + sizeof(coolkey_attribute_header_t));
if (encoded_len) {
*len += 2;
}
return SC_SUCCESS;
case COOLKEY_ATTR_TYPE_BOOL_FALSE:
case COOLKEY_ATTR_TYPE_BOOL_TRUE:
/* NOTE: there is no encoded data from TYPE_BOOL_XXX, so we return length 0, but the length
* of the attribute is actually 1 byte, so if encoded_len == false, return 1 */
*len = encoded_len ? 0: 1;
return SC_SUCCESS;
break;
case COOLKEY_ATTR_TYPE_INTEGER:
*len = 4; /* length is 4 in both encoded length and attribute length */
return SC_SUCCESS;
default:
break;
}
return SC_ERROR_CORRUPTED_DATA;
}
/* length of the attribute data is stored in the header of the v0 record */
static int
coolkey_v0_get_attribute_len(const u8 *attr, size_t buf_len, size_t *len)
{
coolkey_v0_attribute_header_t *attribute_head = (coolkey_v0_attribute_header_t *)attr;
/* don't reference beyond our buffer */
if (buf_len < sizeof(coolkey_v0_attribute_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
*len = bebytes2ushort(attribute_head->attribute_data_len);
return SC_SUCCESS;
}
/* these next 3 functions gets the length of the full attribute record, including
* the attribute header */
static size_t
coolkey_v1_get_attribute_record_len(const u8 *attr, size_t buf_len)
{
size_t attribute_len = sizeof(coolkey_attribute_header_t);
size_t len = 0;
int r;
r = coolkey_v1_get_attribute_len(attr, buf_len, &len, 1);
if (r < 0) {
return buf_len; /* skip to the end, ignore the rest of the record */
}
return MIN(buf_len,attribute_len+len);
}
static size_t
coolkey_v0_get_attribute_record_len(const u8 *attr, size_t buf_len)
{
size_t attribute_len = sizeof(coolkey_v0_attribute_header_t);
size_t len;
int r;
r = coolkey_v0_get_attribute_len(attr, buf_len, &len);
if (r < 0) {
return buf_len; /* skip to the end, ignore the rest of the record */
}
return MIN(buf_len,attribute_len+len);
}
static size_t
coolkey_get_attribute_record_len(const u8 *attr, u8 obj_record_type, size_t buf_len)
{
if (obj_record_type == COOLKEY_V0_OBJECT) {
return coolkey_v0_get_attribute_record_len(attr, buf_len);
}
if (obj_record_type != COOLKEY_V1_OBJECT) {
return buf_len; /* skip to the end */
}
return coolkey_v1_get_attribute_record_len(attr, buf_len);
}
/*
* Attribute type shows up in the same place in all attribute record types. Carry record_type in case
* this changes in the future.
*/
static CK_ATTRIBUTE_TYPE
coolkey_get_attribute_type(const u8 *attr, u8 obj_record_type, size_t buf_len)
{
coolkey_attribute_header_t *attribute_header = (coolkey_attribute_header_t *) attr;
return bebytes2ulong(attribute_header->attribute_attr_type);
}
/*
* return the start of the attribute section based on the record type
*/
static const u8 *
coolkey_attribute_start(const u8 *obj, u8 object_record_type, size_t buf_len)
{
size_t offset = object_record_type == COOLKEY_V1_OBJECT ? sizeof(coolkey_object_header_t) :
sizeof(coolkey_v0_object_header_t);
if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {
return NULL;
}
if (offset > buf_len) {
return NULL;
}
return obj + offset;
}
/*
* We don't have the count in the header for v0 attributes,
* Count them.
*/
static int
coolkey_v0_get_attribute_count(const u8 *obj, size_t buf_len)
{
coolkey_v0_object_header_t *object_head = (coolkey_v0_object_header_t *)obj;
const u8 *attr;
int count = 0;
size_t attribute_data_len;
/* make sure we have enough of the object to read the record_type */
if (buf_len <= sizeof(coolkey_v0_object_header_t)) {
return 0;
}
/*
* now loop through all the attributes in the list. first find the start of the list
*/
attr = coolkey_attribute_start(obj, COOLKEY_V0_OBJECT, buf_len);
if (attr == NULL) {
return 0;
}
buf_len -= (attr-obj);
attribute_data_len = bebytes2ushort(object_head->attribute_data_len);
if (buf_len < attribute_data_len) {
return 0;
}
while (attribute_data_len) {
size_t len = coolkey_v0_get_attribute_record_len(attr, buf_len);
if (len == 0) {
break;
}
/* This is an error in the token data, don't parse the last attribute */
if (len > attribute_data_len) {
break;
}
/* we know that coolkey_v0_get_attribute_record_len never
* returns more than buf_len, so we can safely assert that.
* If the assert is true, you can easily see that the loop
* will eventually break with len == 0, even if attribute_data_len
* was invalid */
assert(len <= buf_len);
count++;
attr += len;
buf_len -= len;
attribute_data_len -= len;
}
return count;
}
static int
coolkey_v1_get_attribute_count(const u8 *obj, size_t buf_len)
{
coolkey_object_header_t *object_head = (coolkey_object_header_t *)obj;
if (buf_len <= sizeof(coolkey_object_header_t)) {
return 0;
}
return bebytes2ushort(object_head->attribute_count);
}
static int
coolkey_get_attribute_count(const u8 *obj, u8 object_record_type, size_t buf_len)
{
if (object_record_type == COOLKEY_V0_OBJECT) {
return coolkey_v0_get_attribute_count(obj, buf_len);
}
if (object_record_type != COOLKEY_V1_OBJECT) {
return 0;
}
return coolkey_v1_get_attribute_count(obj, buf_len);
}
/*
* The next three functions return a parsed attribute value from an attribute record.
*/
static int
coolkey_v0_get_attribute_data(const u8 *attr, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
{
/* we need to manually detect types CK_ULONG */
CK_ATTRIBUTE_TYPE attr_type = coolkey_get_attribute_type(attr, COOLKEY_V0_OBJECT, buf_len);
int r;
size_t len;
attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;
attr_out->attribute_length = 0;
attr_out->attribute_value = NULL;
r = coolkey_v0_get_attribute_len(attr, buf_len, &len);
if (r < 0) {
return r;
}
if ((attr_type == CKA_CLASS) || (attr_type == CKA_CERTIFICATE_TYPE)
|| (attr_type == CKA_KEY_TYPE)) {
if (len != 4) {
return SC_ERROR_CORRUPTED_DATA;
}
attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG;
}
/* return the length and the data */
attr_out->attribute_length = len;
attr_out->attribute_value = attr+sizeof(coolkey_v0_attribute_header_t);
return SC_SUCCESS;
}
static u8 coolkey_static_false = CK_FALSE;
static u8 coolkey_static_true = CK_TRUE;
static int
coolkey_v1_get_attribute_data(const u8 *attr, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
{
int r;
size_t len;
coolkey_attribute_header_t *attribute_head = (coolkey_attribute_header_t *)attr;
if (buf_len < sizeof(coolkey_attribute_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
/* we must have type V1. Process according to data type */
switch (attribute_head->attribute_data_type) {
/* ULONG has implied length of 4 */
case COOLKEY_ATTR_TYPE_INTEGER:
if (buf_len < (sizeof(coolkey_attribute_header_t) + 4)) {
return SC_ERROR_CORRUPTED_DATA;
}
attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG;
attr_out->attribute_length = 4;
attr_out->attribute_value = attr + sizeof(coolkey_attribute_header_t);
return SC_SUCCESS;
/* BOOL_FALSE and BOOL_TRUE have implied length and data */
/* return type STRING for BOOLS */
case COOLKEY_ATTR_TYPE_BOOL_FALSE:
attr_out->attribute_length = 1;
attr_out->attribute_value = &coolkey_static_false;
return SC_SUCCESS;
case COOLKEY_ATTR_TYPE_BOOL_TRUE:
attr_out->attribute_length = 1;
attr_out->attribute_value = &coolkey_static_true;
return SC_SUCCESS;
/* string type has encoded length */
case COOLKEY_ATTR_TYPE_STRING:
r = coolkey_v1_get_attribute_len(attr, buf_len, &len, 0);
if (r < SC_SUCCESS) {
return r;
}
if (buf_len < (len + sizeof(coolkey_attribute_header_t) + 2)) {
return SC_ERROR_CORRUPTED_DATA;
}
attr_out->attribute_value = attr+sizeof(coolkey_attribute_header_t)+2;
attr_out->attribute_length = len;
return SC_SUCCESS;
default:
break;
}
return SC_ERROR_CORRUPTED_DATA;
}
int
coolkey_get_attribute_data(const u8 *attr, u8 object_record_type, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
{
/* handle the V0 objects first */
if (object_record_type == COOLKEY_V0_OBJECT) {
return coolkey_v0_get_attribute_data(attr, buf_len, attr_out);
}
/* don't crash if we encounter some new or corrupted coolkey device */
if (object_record_type != COOLKEY_V1_OBJECT) {
return SC_ERROR_NO_CARD_SUPPORT;
}
return coolkey_v1_get_attribute_data(attr, buf_len, attr_out);
}
/* convert an attribute type into a bit in the fixed attribute uint32_t */
static unsigned long
coolkey_get_fixed_boolean_bit(CK_ATTRIBUTE_TYPE type)
{
switch(type) {
case CKA_TOKEN: return 0x00000080;
case CKA_PRIVATE: return 0x00000100;
case CKA_MODIFIABLE: return 0x00000200;
case CKA_DERIVE: return 0x00000400;
case CKA_LOCAL: return 0x00000800;
case CKA_ENCRYPT: return 0x00001000;
case CKA_DECRYPT: return 0x00002000;
case CKA_WRAP: return 0x00004000;
case CKA_UNWRAP: return 0x00008000;
case CKA_SIGN: return 0x00010000;
case CKA_SIGN_RECOVER: return 0x00020000;
case CKA_VERIFY: return 0x00040000;
case CKA_VERIFY_RECOVER: return 0x00080000;
case CKA_SENSITIVE: return 0x00100000;
case CKA_ALWAYS_SENSITIVE: return 0x00200000;
case CKA_EXTRACTABLE: return 0x00400000;
case CKA_NEVER_EXTRACTABLE: return 0x00800000;
default: break;
}
return 0; /* return no bits */
}
/* This table lets us return a pointer to the CKA_ID value without allocating data or
* creating a changeable static that could cause thread issues */
static const u8 coolkey_static_cka_id[16] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
};
/* This table provides the following:
* 1) a mapping from a 3 bit cka_class to a full 32 bit CKA_CLASS_TYPE value we can return.
* 2) the mask of valid boolean attributes in the fixed attributes.
*/
struct coolkey_fixed_class {
u8 class_value[4];
unsigned long boolean_mask;
};
static const struct coolkey_fixed_class coolkey_static_cka_class[8] = {
{ { 0, 0, 0, 0}, 0x00000380 }, /* DATA */
{ { 0, 0, 0, 1}, 0x00000380 }, /* CERTIFICATE */
{ { 0, 0, 0, 2}, 0x000c5f80 }, /* PUBLIC_KEY */
{ { 0, 0, 0, 3}, 0x00f3af80 }, /* PRIVATE_KEY */
{ { 0, 0, 0, 4}, 0x00f5ff80 }, /* SECRET_KEY */
{ { 0, 0, 0, 5}, 0x00000000 },
{ { 0, 0, 0, 6}, 0x00000000 },
{ { 0, 0, 0, 7}, 0x00000000 }
};
/*
* handle fixed attributes (V1 only)
*/
static int
coolkey_get_attribute_data_fixed(CK_ATTRIBUTE_TYPE attr_type, unsigned long fixed_attributes,
sc_cardctl_coolkey_attribute_t *attr_out) {
unsigned long cka_id = fixed_attributes & 0xf;
unsigned long cka_class = ((fixed_attributes) >> 4) & 0x7;
unsigned long mask, bit;
if (attr_type == CKA_ID) {
attr_out->attribute_length = 1;
attr_out->attribute_value= &coolkey_static_cka_id[cka_id];
return SC_SUCCESS;
}
if (attr_type == CKA_CLASS) {
attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG;
attr_out->attribute_length = 4;
attr_out->attribute_value = coolkey_static_cka_class[cka_class].class_value;
return SC_SUCCESS;
}
/* If it matched, it must be one of the booleans */
mask = coolkey_static_cka_class[cka_class].boolean_mask;
bit = coolkey_get_fixed_boolean_bit(attr_type);
/* attribute isn't in the list */
if ((bit & mask) == 0) {
return SC_ERROR_DATA_OBJECT_NOT_FOUND;
}
attr_out->attribute_length = 1;
attr_out->attribute_value = bit & fixed_attributes ? &coolkey_static_true : &coolkey_static_false;
return SC_SUCCESS;
}
static int
coolkey_v1_get_object_length(u8 *obj, size_t buf_len)
{
coolkey_combined_object_header_t *object_head = (coolkey_combined_object_header_t *) obj;
int attribute_count;
u8 *current_attribute;
int j;
size_t len;
len = sizeof(coolkey_combined_object_header_t);
if (buf_len <= len) {
return buf_len;
}
attribute_count = bebytes2ushort(object_head->attribute_count);
buf_len -= len;
for (current_attribute = obj + len, j = 0; j < attribute_count; j++) {
size_t attribute_len = coolkey_v1_get_attribute_record_len(current_attribute, buf_len);
len += attribute_len;
current_attribute += attribute_len;
buf_len -= attribute_len;
}
return len;
}
/*
* COOLKEY private data per card state
*/
typedef struct coolkey_private_data {
u8 protocol_version_major;
u8 protocol_version_minor;
u8 format_version_major;
u8 format_version_minor;
unsigned short object_version;
u8 life_cycle;
u8 pin_count;
u8 *token_name; /* our token name read from the token */
size_t token_name_length; /* length of our token name */
u8 nonce[COOLKEY_NONCE_SIZE]; /* nonce returned from login */
int nonce_valid;
coolkey_cuid_t cuid; /* card unique ID from the CCC */
sc_cardctl_coolkey_object_t *obj; /* pointer to the current selected object */
list_t objects_list; /* list of objects on the token */
unsigned short key_id; /* key id set by select */
int algorithm; /* saved from set_security_env */
int operation; /* saved from set_security_env */
} coolkey_private_data_t;
#define COOLKEY_DATA(card) ((coolkey_private_data_t*)card->drv_data)
int
coolkey_compare_id(const void * a, const void *b)
{
if (a == NULL || b == NULL)
return 1;
return ((sc_cardctl_coolkey_object_t *)a)->id
== ((sc_cardctl_coolkey_object_t *)b)->id;
}
/* For SimCList autocopy, we need to know the size of the data elements */
size_t coolkey_list_meter(const void *el) {
return sizeof(sc_cardctl_coolkey_object_t);
}
static coolkey_private_data_t *coolkey_new_private_data(void)
{
coolkey_private_data_t *priv;
/* allocate priv and zero all the fields */
priv = calloc(1, sizeof(coolkey_private_data_t));
if (!priv)
return NULL;
/* set other fields as appropriate */
priv->key_id = COOLKEY_INVALID_KEY;
list_init(&priv->objects_list);
list_attributes_comparator(&priv->objects_list, coolkey_compare_id);
list_attributes_copy(&priv->objects_list, coolkey_list_meter, 1);
return priv;
}
static void coolkey_free_private_data(coolkey_private_data_t *priv)
{
list_t *l = &priv->objects_list;
sc_cardctl_coolkey_object_t *o;
/* Clean up the allocated memory in the items */
list_iterator_start(l);
while (list_iterator_hasnext(l)) {
o = (sc_cardctl_coolkey_object_t *)list_iterator_next(l);
free(o->data);
o->data = NULL;
}
list_iterator_stop(l);
list_destroy(&priv->objects_list);
if (priv->token_name) {
free(priv->token_name);
}
free(priv);
return;
}
/*
* Object list operations
*/
static int coolkey_add_object_to_list(list_t *list, const sc_cardctl_coolkey_object_t *object)
{
if (list_append(list, object) < 0)
return SC_ERROR_UNKNOWN;
return SC_SUCCESS;
}
#define COOLKEY_AID "\xA0\x00\x00\x01\x16"
static sc_cardctl_coolkey_object_t *
coolkey_find_object_by_id(list_t *list, unsigned long object_id)
{
int pos;
static sc_cardctl_coolkey_object_t cmp = {{
"", 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ COOLKEY_AID, sizeof(COOLKEY_AID)-1 }
}, 0, 0, NULL};
cmp.id = object_id;
if ((pos = list_locate(list, &cmp)) < 0)
return NULL;
return list_get_at(list, pos);
}
static const sc_path_t coolkey_template_path = {
"", 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ COOLKEY_AID, sizeof(COOLKEY_AID)-1 }
};
struct coolkey_error_codes_st {
int sc_error;
char *description;
};
static const struct coolkey_error_codes_st coolkey_error_codes[]= {
{SC_ERROR_UNKNOWN, "Reserved 0x9c00" },
{SC_ERROR_NOT_ENOUGH_MEMORY, "No memory left on card" },
{SC_ERROR_PIN_CODE_INCORRECT, "Authentication failed" },
{SC_ERROR_NOT_ALLOWED, "Operation not allowed" },
{SC_ERROR_UNKNOWN, "Reserved 0x9c04" },
{SC_ERROR_NO_CARD_SUPPORT, "Unsupported feature" },
{SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Not authorized" },
{SC_ERROR_DATA_OBJECT_NOT_FOUND, "Object not found" },
{SC_ERROR_FILE_ALREADY_EXISTS, "Object exists" },
{SC_ERROR_NO_CARD_SUPPORT, "Incorrect Algorithm" },
{SC_ERROR_UNKNOWN, "Reserved 0x9c0a" },
{SC_ERROR_SM_INVALID_CHECKSUM, "Signature invalid" },
{SC_ERROR_AUTH_METHOD_BLOCKED, "Identity blocked" },
{SC_ERROR_UNKNOWN, "Reserved 0x9c0d" },
{SC_ERROR_UNKNOWN, "Reserved 0x9c0e" },
{SC_ERROR_INCORRECT_PARAMETERS, "Invalid parameter" },
{SC_ERROR_INCORRECT_PARAMETERS, "Incorrect P1" },
{SC_ERROR_INCORRECT_PARAMETERS, "Incorrect P2" },
{SC_ERROR_FILE_END_REACHED, "Sequence End" },
};
static const unsigned int
coolkey_number_of_error_codes = sizeof(coolkey_error_codes)/sizeof(coolkey_error_codes[0]);
static int coolkey_check_sw(sc_card_t *card, unsigned int sw1, unsigned int sw2)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"sw1 = 0x%02x, sw2 = 0x%02x\n", sw1, sw2);
if (sw1 == 0x90)
return SC_SUCCESS;
if (sw1 == 0x9c) {
if (sw2 == 0xff) {
/* shouldn't happen on a production applet, 0x9cff is a debugging error code */
return SC_ERROR_INTERNAL;
}
if (sw2 >= coolkey_number_of_error_codes) {
return SC_ERROR_UNKNOWN;
}
return coolkey_error_codes[sw2].sc_error;
}
/* iso error */
return sc_get_iso7816_driver()->ops->check_sw(card, sw1, sw2);
}
/*
* Send a command and receive data.
*
* 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.
*
* modelled after a similar function in card-piv.c. The coolkey version
* adds the coolkey nonce to user authenticated operations.
*/
static int coolkey_apdu_io(sc_card_t *card, int cla, int ins, int p1, int p2,
const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen,
const u8 *nonce, size_t nonce_len)
{
int r;
sc_apdu_t apdu;
u8 rbufinitbuf[COOLKEY_MAX_SIZE];
u8 rsendbuf[COOLKEY_MAX_SIZE];
u8 *rbuf;
size_t rbuflen;
int cse = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
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;
}
if (sendbuf || nonce) {
if (recvbuf) {
cse = SC_APDU_CASE_4_SHORT;
} else {
cse = SC_APDU_CASE_3_SHORT;
}
} else {
if (recvbuf) {
cse = SC_APDU_CASE_2_SHORT;
} else {
cse = SC_APDU_CASE_1;
}
}
/* append the nonce if we have it. Coolkey just blindly puts this at the end
* of the APDU (while adjusting lc). This converts case 1 to case 3. coolkey
* also always drops le in case 4 (which happens when proto = T0). nonces are
* never used on case 2 commands, so we can simply append the nonce to the data
* and we should be fine */
if (nonce) {
u8 *buf = rsendbuf;
if (sendbuf) {
sendbuflen = MIN(sendbuflen,sizeof(rsendbuf)-nonce_len);
memcpy(rsendbuf, sendbuf, sendbuflen);
buf += sendbuflen;
}
memcpy(buf, nonce, nonce_len);
sendbuflen += nonce_len;
sendbuf =rsendbuf;
}
sc_format_apdu(card, &apdu, cse, ins, p1, p2);
apdu.lc = sendbuflen;
apdu.datalen = sendbuflen;
apdu.data = sendbuf;
/* coolkey uses non-standard classes */
apdu.cla = cla;
if (recvbuf) {
apdu.resp = rbuf;
apdu.le = (rbuflen > 255) ? 255 : rbuflen;
apdu.resplen = rbuflen;
} else {
apdu.resp = rbuf;
apdu.le = 0;
apdu.resplen = 0;
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"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_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"result 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_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
goto err;
}
if (recvbuflen) {
if (recvbuf && *recvbuf == NULL) {
*recvbuf = malloc(apdu.resplen);
if (*recvbuf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*recvbuf, rbuf, apdu.resplen);
}
*recvbuflen = apdu.resplen;
r = *recvbuflen;
}
err:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Helpers to handle coolkey commands
*/
static int
coolkey_get_life_cycle(sc_card_t *card, coolkey_life_cycle_t *life_cycle)
{
coolkey_status_t status;
u8 *receive_buf;
size_t len;
int r;
len = sizeof(*life_cycle);
receive_buf = (u8 *)life_cycle;
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_LIFE_CYCLE, 0, 0,
NULL, 0, &receive_buf, &len, NULL, 0);
if (r == sizeof(*life_cycle)) {
return SC_SUCCESS;
}
len = 1;
receive_buf = &life_cycle->life_cycle;
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_LIFE_CYCLE, 0, 0,
NULL, 0, &receive_buf, &len, NULL, 0);
if (r < 0) {
return r;
}
len = sizeof(status);
receive_buf = (u8 *)&status;
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_STATUS, 0, 0,
NULL, 0, &receive_buf, &len, NULL, 0);
if (r < 0) {
return r;
}
life_cycle->protocol_version_major = status.protocol_version_major;
life_cycle->protocol_version_minor = status.protocol_version_minor;
life_cycle->pin_count = status.pin_count;
return SC_SUCCESS;
}
/* should be general global platform call */
static int
coolkey_get_cplc_data(sc_card_t *card, global_platform_cplc_data_t *cplc_data)
{
size_t len = sizeof(global_platform_cplc_data_t);
u8 *receive_buf = (u8 *)cplc_data;
return coolkey_apdu_io(card, GLOBAL_PLATFORM_CLASS, ISO7816_INS_GET_DATA, 0x9f, 0x7f,
NULL, 0, &receive_buf, &len, NULL, 0);
}
/* select the coolkey applet */
static int coolkey_select_applet(sc_card_t *card)
{
u8 aid[] = { 0x62, 0x76, 0x01, 0xff, 0x00, 0x00, 0x00 };
return coolkey_apdu_io(card, ISO7816_CLASS, ISO7816_INS_SELECT_FILE, 4, 0,
&aid[0], sizeof(aid), NULL, NULL, NULL, 0);
}
static void
coolkey_make_cuid_from_cplc(coolkey_cuid_t *cuid, global_platform_cplc_data_t *cplc_data)
{
cuid->ic_fabricator[0] = cplc_data->ic_fabricator[0];
cuid->ic_fabricator[1] = cplc_data->ic_fabricator[1];
cuid->ic_type[0] = cplc_data->ic_type[0];
cuid->ic_type[1] = cplc_data->ic_type[1];
cuid->ic_batch[0] = cplc_data->ic_batch[0];
cuid->ic_batch[1] = cplc_data->ic_batch[1];
cuid->ic_serial_number[0] = cplc_data->ic_serial_number[0];
cuid->ic_serial_number[1] = cplc_data->ic_serial_number[1];
cuid->ic_serial_number[2] = cplc_data->ic_serial_number[2];
cuid->ic_serial_number[3] = cplc_data->ic_serial_number[3];
}
/*
* Read a COOLKEY coolkey object.
*/
static int coolkey_read_object(sc_card_t *card, unsigned long object_id, size_t offset,
u8 *out_buf, size_t out_len, u8 *nonce, size_t nonce_size)
{
coolkey_read_object_param_t params;
u8 *out_ptr;
size_t left = 0;
size_t len;
int r;
ulong2bebytes(¶ms.object_id[0], object_id);
out_ptr = out_buf;
left = out_len;
do {
ulong2bebytes(¶ms.offset[0], offset);
params.length = MIN(left, COOLKEY_MAX_CHUNK_SIZE);
len = left+2;
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_READ_OBJECT, 0, 0,
(u8 *)¶ms, sizeof(params), &out_ptr, &len, nonce, nonce_size);
if (r < 0) {
goto fail;
}
/* sanity check to make sure we don't overflow left */
if ((left < len) || (len == 0)) {
r = SC_ERROR_INTERNAL;
goto fail;
}
out_ptr += len;
offset += len;
left -= len;
} while (left != 0);
return out_len;
fail:
return r;
}
/*
* Write a COOLKEY coolkey object.
*/
static int coolkey_write_object(sc_card_t *card, unsigned long object_id,
size_t offset, const u8 *buf, size_t buf_len, const u8 *nonce, size_t nonce_size)
{
coolkey_write_object_param_t params;
size_t operation_len;
size_t left = buf_len;
int r;
ulong2bebytes(¶ms.head.object_id[0], object_id);
do {
ulong2bebytes(¶ms.head.offset[0], offset);
operation_len = MIN(left, COOLKEY_MAX_CHUNK_SIZE);
params.head.length = operation_len;
memcpy(params.buf, buf, operation_len);
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_WRITE_OBJECT, 0, 0,
(u8 *)¶ms, sizeof(params.head)+operation_len, NULL, 0, nonce, nonce_size);
if (r < 0) {
goto fail;
}
buf += operation_len;
offset += operation_len;
left -= operation_len;
} while (left != 0);
return buf_len - left;
fail:
return r;
}
/*
* coolkey_read_binary will read a coolkey object off the card. That object is selected
* by select file. If we've already read the object, we'll return the data from the cache.
* coolkey objects are encoded PKCS #11 entries, not pkcs #15 data. pkcs15-coolkey will
* translate the objects into their PKCS #15 equivalent data structures.
*/
static int coolkey_read_binary(sc_card_t *card, unsigned int idx,
u8 *buf, size_t count, unsigned long flags)
{
coolkey_private_data_t * priv = COOLKEY_DATA(card);
int r = 0, len;
u8 *data = NULL;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (idx > priv->obj->length) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED);
}
/* if we've already read the data, just return it */
if (priv->obj->data) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"returning cached value idx=%u count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
len = MIN(count, priv->obj->length-idx);
memcpy(buf, &priv->obj->data[idx], len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len);
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"clearing cache idx=%u count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
data = malloc(priv->obj->length);
if (data == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
r = coolkey_read_object(card, priv->obj->id, 0, data, priv->obj->length,
priv->nonce, sizeof(priv->nonce));
if (r < 0)
goto done;
if ((size_t) r != priv->obj->length) {
priv->obj->length = r;
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
len = MIN(count, priv->obj->length-idx);
memcpy(buf, &data[idx], len);
r = len;
/* cache the data in the object */
priv->obj->data=data;
data = NULL;
done:
if (data)
free(data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* COOLKEY driver is read only. NOTE: The applet supports w/r operations, so it's perfectly
* reasonable to try to create new objects, but currently TPS does not create applets
* That allow user created objects, so this is a nice 2.0 feature. */
static int coolkey_write_binary(sc_card_t *card, unsigned int idx,
const u8 *buf, size_t count, unsigned long flags)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
/* initialize getting a list and return the number of elements in the list */
static int coolkey_get_init_and_get_count(list_t *list, int *countp)
{
*countp = list_size(list);
list_iterator_start(list);
return SC_SUCCESS;
}
/* fill in the obj_info for the current object on the list and advance to the next object */
static int coolkey_fetch_object(list_t *list, sc_cardctl_coolkey_object_t *coolkey_obj)
{
sc_cardctl_coolkey_object_t *ptr;
if (!list_iterator_hasnext(list)) {
return SC_ERROR_FILE_END_REACHED;
}
ptr = list_iterator_next(list);
*coolkey_obj = *ptr;
return SC_SUCCESS;
}
/* Finalize iterator */
static int coolkey_final_iterator(list_t *list)
{
list_iterator_stop(list);
return SC_SUCCESS;
}
static char * coolkey_cuid_to_string(coolkey_cuid_t *cuid)
{
char *buf;
size_t len = sizeof(coolkey_cuid_t)*2 + 1;
buf = malloc(len);
if (buf == NULL) {
return NULL;
}
sc_bin_to_hex((u8 *)cuid, sizeof(*cuid), buf, len, 0);
return buf;
}
static const struct manufacturer_list_st {
unsigned short id;
char *string;
} manufacturer_list[] = {
{ 0x2050, "%04x Oberthur" },
{ 0x4090, "%04x GemAlto (Infineon)" },
{ 0x4780, "%04x STMicroElectronics" },
{ 0x4780, "%04x RSA" },
{ 0x534e, "%04x SafeNet" },
};
int manufacturer_list_count = sizeof(manufacturer_list)/sizeof(manufacturer_list[0]);
static char * coolkey_get_manufacturer(coolkey_cuid_t *cuid)
{
unsigned short fabricator = bebytes2ushort(cuid->ic_fabricator);
int i;
char *buf;
const char *manufacturer_string = "%04x Unknown";
size_t len;
int r;
for (i=0; i < manufacturer_list_count; i++) {
if (manufacturer_list[i].id == fabricator) {
manufacturer_string = manufacturer_list[i].string;
break;
}
}
len = strlen(manufacturer_string)+1;
buf= malloc(len);
if (buf == NULL) {
return NULL;
}
r = snprintf(buf, len, manufacturer_string, fabricator);
if (r < 0) {
free(buf);
return NULL;
}
return buf;
}
static int coolkey_get_token_info(sc_card_t *card, sc_pkcs15_tokeninfo_t * token_info)
{
coolkey_private_data_t * priv = COOLKEY_DATA(card);
char *label = NULL;
char *manufacturer_id = NULL;
char *serial_number = NULL;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
label = strdup((char *)priv->token_name);
manufacturer_id = coolkey_get_manufacturer(&priv->cuid);
serial_number = coolkey_cuid_to_string(&priv->cuid);
if (label && manufacturer_id && serial_number) {
token_info->label = label;
token_info->manufacturer_id = manufacturer_id;
token_info->serial_number = serial_number;
return SC_SUCCESS;
}
free(label);
free(manufacturer_id);
free(serial_number);
return SC_ERROR_OUT_OF_MEMORY;
}
static int coolkey_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
coolkey_private_data_t * priv = COOLKEY_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
memcpy(serial->value, &priv->cuid, sizeof(priv->cuid));
serial->len = sizeof(priv->cuid);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
int
coolkey_fill_object(sc_card_t *card, sc_cardctl_coolkey_object_t *obj)
{
int r;
size_t buf_len = obj->length;
u8 *new_obj_data = NULL;
sc_cardctl_coolkey_object_t *obj_entry;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
if (obj->data != NULL) {
return SC_SUCCESS;
}
new_obj_data = malloc(buf_len);
if (new_obj_data == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
r = coolkey_read_object(card, obj->id, 0, new_obj_data, buf_len,
priv->nonce, sizeof(priv->nonce));
if (r != (int)buf_len) {
free(new_obj_data);
return SC_ERROR_CORRUPTED_DATA;
}
obj_entry = coolkey_find_object_by_id(&priv->objects_list, obj->id);
if (obj_entry == NULL) {
free(new_obj_data);
return SC_ERROR_INTERNAL; /* shouldn't happen */
}
if (obj_entry->data != NULL) {
free(new_obj_data);
return SC_ERROR_INTERNAL; /* shouldn't happen */
}
obj_entry->data = new_obj_data;
obj->data = new_obj_data;
return SC_SUCCESS;
}
/*
* return a parsed record for the attribute which includes value, type, and length.
* Handled both v1 and v0 record types. determine record type from the object.
* make sure we don't overrun the buffer if the token gives us bad data.
*/
static int
coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute)
{
u8 object_record_type;
CK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type;
const u8 *obj = attribute->object->data;
const u8 *attr = NULL;
size_t buf_len = attribute->object->length;
coolkey_object_header_t *object_head;
int attribute_count,i;
attribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;
attribute->attribute_length = 0;
attribute->attribute_value = NULL;
if (obj == NULL) {
/* cast away const so we can cache the data value */
int r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object);
if (r < 0) {
return r;
}
obj = attribute->object->data;
}
/* should be a static assert so we catch this at compile time */
assert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t));
/* make sure we have enough of the object to read the record_type */
if (buf_len <= sizeof(coolkey_v0_object_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
object_head = (coolkey_object_header_t *)obj;
object_record_type = object_head->record_type;
/* make sure it's a type we recognize */
if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {
return SC_ERROR_CORRUPTED_DATA;
}
/*
* now loop through all the attributes in the list. first find the start of the list
*/
attr = coolkey_attribute_start(obj, object_record_type, buf_len);
if (attr == NULL) {
return SC_ERROR_CORRUPTED_DATA;
}
buf_len -= (attr-obj);
/* now get the count */
attribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len);
for (i=0; i < attribute_count; i++) {
size_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len);
/* make sure we have the complete record */
if (buf_len < record_len || record_len < 4) {
return SC_ERROR_CORRUPTED_DATA;
}
/* does the attribute match the one we are looking for */
if (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) {
/* yup, return it */
return coolkey_get_attribute_data(attr, object_record_type, record_len, attribute);
}
/* go to the next attribute on the list */
buf_len -= record_len;
attr += record_len;
}
/* not find in attribute list, check the fixed attribute record */
if (object_record_type == COOLKEY_V1_OBJECT) {
unsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values);
return coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute);
}
return SC_ERROR_DATA_OBJECT_NOT_FOUND;
}
/*
* pkcs 15 needs to find the cert matching the keys to fill in some of the fields that wasn't stored
* with the key. To do this we need to look for the cert matching the key's CKA_ID. For flexibility,
* We simply search using a pkcs #11 style template using the cardctl_coolkey_attribute_t structure */
sc_cardctl_coolkey_object_t *
coolkey_find_object_by_template(sc_card_t *card, sc_cardctl_coolkey_attribute_t *template, int count)
{
list_t *list;
sc_cardctl_coolkey_object_t *current, *rv = NULL;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
int i, r;
unsigned int tmp_pos = (unsigned int) -1;
list = &priv->objects_list;
if (list->iter_active) {
/* workaround missing functionality of second iterator */
tmp_pos = list->iter_pos;
list_iterator_stop(list);
}
list_iterator_start(list);
while (list_iterator_hasnext(list)) {
sc_cardctl_coolkey_attribute_t attribute;
current = list_iterator_next(list);
attribute.object = current;
for (i=0; i < count; i++) {
attribute.attribute_type = template[i].attribute_type;
r = coolkey_find_attribute(card, &attribute);
if (r < 0) {
break;
}
if (template[i].attribute_data_type != attribute.attribute_data_type) {
break;
}
if (template[i].attribute_length != attribute.attribute_length) {
break;
}
if (memcmp(attribute.attribute_value, template[i].attribute_value,
attribute.attribute_length) != 0) {
break;
}
}
/* just return the first one */
if (i == count) {
rv = current;
break;
}
}
list_iterator_stop(list);
if (tmp_pos != (unsigned int)-1) {
/* workaround missing functionality of second iterator */
list_iterator_start(list);
while (list_iterator_hasnext(list) && list->iter_pos < tmp_pos)
(void) list_iterator_next(list);
}
return rv;
}
static int
coolkey_find_object(sc_card_t *card, sc_cardctl_coolkey_find_object_t *fobj)
{
sc_cardctl_coolkey_object_t *obj = NULL;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
int r;
switch (fobj->type) {
case SC_CARDCTL_COOLKEY_FIND_BY_ID:
obj = coolkey_find_object_by_id(&priv->objects_list, fobj->find_id);
break;
case SC_CARDCTL_COOLKEY_FIND_BY_TEMPLATE:
obj = coolkey_find_object_by_template(card, fobj->coolkey_template, fobj->template_count);
break;
default:
break;
}
if (obj == NULL) {
return SC_ERROR_DATA_OBJECT_NOT_FOUND;
}
if (obj->data == NULL) {
r = coolkey_fill_object(card, obj);
if (r < 0) {
return r;
}
}
fobj->obj = obj;
return SC_SUCCESS;
}
static int coolkey_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
coolkey_private_data_t * priv = COOLKEY_DATA(card);
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_GET_SERIALNR:
return coolkey_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
case SC_CARDCTL_COOLKEY_GET_TOKEN_INFO:
return coolkey_get_token_info(card, (sc_pkcs15_tokeninfo_t *) ptr);
case SC_CARDCTL_COOLKEY_FIND_OBJECT:
return coolkey_find_object(card, (sc_cardctl_coolkey_find_object_t *)ptr);
case SC_CARDCTL_COOLKEY_INIT_GET_OBJECTS:
return coolkey_get_init_and_get_count(&priv->objects_list, (int *)ptr);
case SC_CARDCTL_COOLKEY_GET_NEXT_OBJECT:
return coolkey_fetch_object(&priv->objects_list, (sc_cardctl_coolkey_object_t *)ptr);
case SC_CARDCTL_COOLKEY_FINAL_GET_OBJECTS:
return coolkey_final_iterator(&priv->objects_list);
case SC_CARDCTL_COOLKEY_GET_ATTRIBUTE:
return coolkey_find_attribute(card,(sc_cardctl_coolkey_attribute_t *)ptr);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
static int coolkey_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
LOG_FUNC_CALLED(card->ctx);
if (len > COOLKEY_MAX_CHUNK_SIZE)
len = COOLKEY_MAX_CHUNK_SIZE;
LOG_TEST_RET(card->ctx,
coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_RANDOM, 0, 0,
NULL, 0, &rnd, &len, NULL, 0),
"Could not get challenge");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) len);
}
static int coolkey_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
int r = SC_SUCCESS;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
env->flags, env->operation, env->algorithm,
env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
env->key_ref_len);
if ((env->algorithm != SC_ALGORITHM_RSA) && (env->algorithm != SC_ALGORITHM_EC)) {
r = SC_ERROR_NO_CARD_SUPPORT;
}
priv->algorithm = env->algorithm;
priv->operation = env->operation;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int coolkey_restore_security_env(sc_card_t *card, int se_num)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
#define MAX_COMPUTE_BUF 200
typedef struct coolkey_compute_crypt_init_params {
u8 mode;
u8 direction;
u8 location;
u8 buf_len[2];
} coolkey_compute_crypt_init_params_t;
typedef struct coolkey_compute_crypt_params {
coolkey_compute_crypt_init_params_t init;
u8 buf[MAX_COMPUTE_BUF];
} coolkey_compute_crypt_params_t;
typedef struct coolkey_compute_ecc_params {
u8 location;
u8 buf_len[2];
u8 buf[MAX_COMPUTE_BUF];
} coolkey_compute_ecc_params_t;
static int coolkey_rsa_op(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t max_out_len)
{
int r;
const u8 *crypt_in;
u8 **crypt_out_p;
size_t crypt_in_len, *crypt_out_len_p;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
coolkey_compute_crypt_params_t params;
u8 key_number;
size_t params_len;
size_t buf_len;
u8 buf[MAX_COMPUTE_BUF+2];
u8 *buf_out;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
datalen, max_out_len);
crypt_in = data;
crypt_in_len = datalen;
buf_out = &buf[0];
crypt_out_p = &buf_out;
buf_len = sizeof(buf);
crypt_out_len_p = &buf_len;
key_number = priv->key_id;
params.init.mode = COOLKEY_CRYPT_MODE_RSA_NO_PAD;
params.init.location = COOLKEY_CRYPT_LOCATION_APDU;
params.init.direction = COOLKEY_CRYPT_DIRECTION_ENCRYPT; /* for no pad, direction is irrelevant */
if (priv->key_id > 0xff) {
r = SC_ERROR_NO_DEFAULT_KEY;
goto done;
}
params_len = sizeof(params.init) + crypt_in_len;
/* send the data to the card if necessary */
if (crypt_in_len > MAX_COMPUTE_BUF) {
u8 len_buf[2];
params.init.location = COOLKEY_CRYPT_LOCATION_DL_OBJECT;
params_len = sizeof(params.init);
crypt_in = NULL;
crypt_in_len = 0;
*crypt_out_p = NULL;
*crypt_out_len_p = 0;
ushort2bebytes(len_buf, datalen);
r = coolkey_write_object(card, COOLKEY_DL_OBJECT_ID, 0, len_buf, sizeof(len_buf),
priv->nonce, sizeof(priv->nonce));
if (r < 0) {
goto done;
}
r = coolkey_write_object(card, COOLKEY_DL_OBJECT_ID, 2, data, datalen, priv->nonce,
sizeof(priv->nonce));
if (r < 0) {
goto done;
}
}
ushort2bebytes(params.init.buf_len, crypt_in_len);
if (crypt_in_len) {
memcpy(params.buf, crypt_in, crypt_in_len);
}
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_COMPUTE_CRYPT,
key_number, COOLKEY_CRYPT_ONE_STEP, (u8 *)¶ms, params_len,
crypt_out_p, crypt_out_len_p, priv->nonce, sizeof(priv->nonce));
if (r < 0) {
goto done;
}
if (datalen > MAX_COMPUTE_BUF) {
u8 len_buf[2];
size_t out_length;
r = coolkey_read_object(card, COOLKEY_DL_OBJECT_ID, 0, len_buf, sizeof(len_buf),
priv->nonce, sizeof(priv->nonce));
if (r < 0) {
goto done;
}
out_length = bebytes2ushort(len_buf);
out_length = MIN(out_length,max_out_len);
r = coolkey_read_object(card, COOLKEY_DL_OBJECT_ID, sizeof(len_buf), out, out_length,
priv->nonce, sizeof(priv->nonce));
} else {
size_t out_length = bebytes2ushort(buf);
out_length = MIN(out_length, max_out_len);
memcpy(out, buf+2, out_length);
r = out_length;
}
done:
return r;
}
static int coolkey_ecc_op(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
const u8 *crypt_in;
u8 **crypt_out_p;
u8 ins = 0;
size_t crypt_in_len, *crypt_out_len_p;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
coolkey_compute_ecc_params_t params;
size_t params_len;
u8 key_number;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
datalen, outlen);
crypt_in = data;
crypt_in_len = datalen;
crypt_out_p = &out;
crypt_out_len_p = &outlen;
key_number = priv->key_id;
params.location = COOLKEY_CRYPT_LOCATION_APDU;
if (priv->key_id > 0xff) {
r = SC_ERROR_NO_DEFAULT_KEY;
goto done;
}
switch (priv->operation) {
case SC_SEC_OPERATION_DERIVE:
ins = COOLKEY_INS_COMPUTE_ECC_KEY_AGREEMENT;
break;
case SC_SEC_OPERATION_SIGN:
ins = COOLKEY_INS_COMPUTE_ECC_SIGNATURE;
break;
default:
r = SC_ERROR_NOT_SUPPORTED;
goto done;
}
params_len = (sizeof(params) - sizeof(params.buf)) + crypt_in_len;
ushort2bebytes(params.buf_len, crypt_in_len);
if (crypt_in_len) {
memcpy(params.buf, crypt_in, crypt_in_len);
}
r = coolkey_apdu_io(card, COOLKEY_CLASS, ins,
key_number, COOLKEY_CRYPT_ONE_STEP, (u8 *)¶ms, params_len,
crypt_out_p, crypt_out_len_p, priv->nonce, sizeof(priv->nonce));
done:
return r;
}
static int coolkey_compute_crypt(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
coolkey_private_data_t * priv = COOLKEY_DATA(card);
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
switch (priv->algorithm) {
case SC_ALGORITHM_RSA:
r = coolkey_rsa_op(card, data, datalen, out, outlen);
break;
case SC_ALGORITHM_EC:
r = coolkey_ecc_op(card, data, datalen, out, outlen);
break;
default:
r = SC_ERROR_NO_CARD_SUPPORT;
break;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static u8 coolkey_class(unsigned long object_id) {
return (object_id >> 24) & 0xff;
}
static unsigned short coolkey_get_key_id(unsigned long object_id) {
char char_index = (object_id >> 16) & 0xff;
if (char_index >= '0' && char_index <= '9') {
return (u8)(char_index - '0');
}
if (char_index >= 'A' && char_index <= 'Z') {
return (u8)(char_index - 'A' + 10);
}
if (char_index >= 'a' && char_index <= 'z') {
return (u8)(char_index - 'a' + 26 + 10);
}
return COOLKEY_INVALID_KEY;
}
/*
* COOLKEY cards don't select objects in the applet, objects are selected by a parameter
* to the APDU. We create paths for the object in which the path value is the object_id
* and the path type is SC_PATH_SELECT_FILE_ID (so we could cache at the PKCS #15 level if
* we wanted to.
*
* This select simply records what object was selected so that read knows how to access it.
*/
static int coolkey_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
int r;
struct sc_file *file = NULL;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
unsigned long object_id;
assert(card != NULL && in_path != NULL);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (in_path->len != 4) {
return SC_ERROR_OBJECT_NOT_FOUND;
}
r = coolkey_select_applet(card);
if (r != SC_SUCCESS) {
return r;
}
object_id = bebytes2ulong(in_path->value);
priv->obj = coolkey_find_object_by_id(&priv->objects_list, object_id);
if (priv->obj == NULL) {
return SC_ERROR_OBJECT_NOT_FOUND;
}
priv->key_id = COOLKEY_INVALID_KEY;
if (coolkey_class(object_id) == COOLKEY_KEY_CLASS) {
priv->key_id = coolkey_get_key_id(object_id);
}
if (file_out) {
file = sc_file_new();
if (file == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
/* this could be like the FCI */
file->type = SC_PATH_TYPE_FILE_ID;
file->shareable = 0;
file->ef_structure = 0;
file->size = priv->obj->length;
*file_out = file;
}
return SC_SUCCESS;
}
static int coolkey_finish(sc_card_t *card)
{
coolkey_private_data_t * priv = COOLKEY_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
coolkey_free_private_data(priv);
}
return SC_SUCCESS;
}
static int
coolkey_add_object(coolkey_private_data_t *priv, unsigned long object_id, const u8 *object_data, size_t object_length, int add_v1_record)
{
sc_cardctl_coolkey_object_t new_object;
int r;
memset(&new_object, 0, sizeof(new_object));
new_object.path = coolkey_template_path;
new_object.path.len = 4;
ulong2bebytes(new_object.path.value, object_id);
new_object.id = object_id;
new_object.length = object_length;
if (object_data) {
new_object.data = malloc(object_length + add_v1_record);
if (new_object.data == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
if (add_v1_record) {
new_object.data[0] = COOLKEY_V1_OBJECT;
new_object.length++;
}
memcpy(&new_object.data[add_v1_record], object_data, object_length);
}
r = coolkey_add_object_to_list(&priv->objects_list, &new_object);
if (r != SC_SUCCESS) {
/* if we didn't successfully put the object on the list,
* the data space didn't get adopted. free it before we return */
free(new_object.data);
new_object.data = NULL;
}
return r;
}
static int
coolkey_process_combined_object(sc_card_t *card, coolkey_private_data_t *priv, u8 *object, size_t object_length)
{
coolkey_combined_header_t *header = (coolkey_combined_header_t *)object;
unsigned short compressed_offset;
unsigned short compressed_length;
unsigned short compressed_type;
unsigned short object_offset;
unsigned short object_count;
coolkey_decompressed_header_t *decompressed_header;
u8 *decompressed_object = NULL;
size_t decompressed_object_len = 0;
int free_decompressed = 0;
int i, r;
if (object_length < sizeof(coolkey_combined_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
compressed_offset = bebytes2ushort(header->compression_offset);
compressed_length = bebytes2ushort(header->compression_length);
compressed_type = bebytes2ushort(header->compression_type);
if ((((size_t)compressed_offset) + (size_t)compressed_length) > object_length) {
return SC_ERROR_CORRUPTED_DATA;
}
/* store the CUID */
memcpy(&priv->cuid, &header->cuid, sizeof(priv->cuid));
if (compressed_type == COOLKEY_COMPRESSION_ZLIB) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&decompressed_object, &decompressed_object_len, &object[compressed_offset], compressed_length, COMPRESSION_AUTO);
if (r)
goto done;
free_decompressed = 1;
#else
sc_log(card->ctx, "Coolkey compression not supported, no zlib");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
#endif
} else {
decompressed_object =&object[compressed_offset];
decompressed_object_len = (size_t) compressed_length;
}
decompressed_header = (coolkey_decompressed_header_t *)decompressed_object;
if (decompressed_object_len < sizeof(coolkey_decompressed_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
object_offset = bebytes2ushort(decompressed_header->object_offset);
object_count = bebytes2ushort(decompressed_header->object_count);
/*
* using 2 different tests here so we can log different errors if logging is
* turned on.
*/
/* make sure token_name doesn't overrun the buffer */
if (decompressed_header->token_name_length +
offsetof(coolkey_decompressed_header_t,token_name) > decompressed_object_len) {
r = SC_ERROR_CORRUPTED_DATA;
goto done;
}
/* make sure it doesn't overlap the object space */
if (decompressed_header->token_name_length +
offsetof(coolkey_decompressed_header_t,token_name) > object_offset) {
r = SC_ERROR_CORRUPTED_DATA;
goto done;
}
/* store the token name in the priv structure so the emulator can set it */
priv->token_name = malloc(decompressed_header->token_name_length+1);
if (priv->token_name == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
memcpy(priv->token_name, &decompressed_header->token_name[0],
decompressed_header->token_name_length);
priv->token_name[decompressed_header->token_name_length] = 0;
priv->token_name_length = decompressed_header->token_name_length;
for (i=0; i < object_count && object_offset < decompressed_object_len; i++ ) {
u8 *current_object = &decompressed_object[object_offset];
coolkey_combined_object_header_t *object_header =
(coolkey_combined_object_header_t *)current_object;
unsigned long object_id = bebytes2ulong(object_header->object_id);
int current_object_len;
/* figure out how big it is */
r = coolkey_v1_get_object_length(current_object, decompressed_object_len-object_offset);
if (r < 0) {
goto done;
}
if ((size_t)r + object_offset > decompressed_object_len) {
r = SC_ERROR_CORRUPTED_DATA;
goto done;
}
current_object_len = r;
object_offset += current_object_len;
/* record this object */
r = coolkey_add_object(priv, object_id, current_object, current_object_len, 1);
if (r) {
goto done;
}
}
r = SC_SUCCESS;
done:
if (free_decompressed) {
free(decompressed_object);
}
return r;
}
static int
coolkey_list_object(sc_card_t *card, u8 seq, coolkey_object_info_t *object_info)
{
u8 *rbuf = (u8 *) object_info;
size_t rbuflen = sizeof(*object_info);
return coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_LIST_OBJECTS, seq, 0,
NULL, 0, &rbuf, &rbuflen, NULL, 0);
}
/*
* Initialize the Coolkey data structures.
*/
static int coolkey_initialize(sc_card_t *card)
{
int r;
coolkey_private_data_t *priv = NULL;
coolkey_life_cycle_t life_cycle;
coolkey_object_info_t object_info;
int combined_processed = 0;
/* already found? */
if (card->drv_data) {
return SC_SUCCESS;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"Coolkey Applet found");
priv = coolkey_new_private_data();
if (priv == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto cleanup;
}
r = coolkey_get_life_cycle(card, &life_cycle);
if (r < 0) {
goto cleanup;
}
/* Select a coolkey read the coolkey objects out */
r = coolkey_select_applet(card);
if (r < 0) {
goto cleanup;
}
priv->protocol_version_major = life_cycle.protocol_version_major;
priv->protocol_version_minor = life_cycle.protocol_version_minor;
priv->pin_count = life_cycle.pin_count;
priv->life_cycle = life_cycle.life_cycle;
/* walk down the list of objects and read them off the token */
for(r=coolkey_list_object(card, COOLKEY_LIST_RESET, &object_info); r >= 0;
r= coolkey_list_object(card, COOLKEY_LIST_NEXT, &object_info)) {
unsigned long object_id = bebytes2ulong(object_info.object_id);
unsigned short object_len = bebytes2ulong(object_info.object_length);
/* also look at the ACL... */
/* the combined object is a single object that can store the other objects.
* most coolkeys provisioned by TPS has a single combined object that is
* compressed greatly increasing the effectiveness of compress (since lots
* of certs on the token share the same Subject and Issuer DN's). We now
* process it separately so that we can have both combined objects managed
* by TPS and user managed certs on the same token */
if (object_id == COOLKEY_COMBINED_OBJECT_ID) {
u8 *object = malloc(object_len);
if (object == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
break;
}
r = coolkey_read_object(card, COOLKEY_COMBINED_OBJECT_ID, 0, object, object_len,
priv->nonce, sizeof(priv->nonce));
if (r < 0) {
free(object);
break;
}
r = coolkey_process_combined_object(card, priv, object, r);
free(object);
if (r != SC_SUCCESS) {
break;
}
combined_processed = 1;
continue;
}
r = coolkey_add_object(priv, object_id, NULL, object_len, 0);
if (r != SC_SUCCESS)
sc_log(card->ctx, "coolkey_add_object() returned %d", r);
}
if (r != SC_ERROR_FILE_END_REACHED) {
goto cleanup;
}
/* if we didn't pull the cuid from the combined object, then grab it now */
if (!combined_processed) {
global_platform_cplc_data_t cplc_data;
/* select the card manager, because a card with applet only will have
already selected the coolkey applet */
r = gp_select_card_manager(card);
if (r < 0) {
goto cleanup;
}
r = coolkey_get_cplc_data(card, &cplc_data);
if (r < 0) {
goto cleanup;
}
coolkey_make_cuid_from_cplc(&priv->cuid, &cplc_data);
priv->token_name = (u8 *)strdup("COOLKEY");
if (priv->token_name == NULL) {
r= SC_ERROR_OUT_OF_MEMORY;
goto cleanup;
}
priv->token_name_length = sizeof("COOLKEY")-1;
}
card->drv_data = priv;
return SC_SUCCESS;
cleanup:
if (priv) {
coolkey_free_private_data(priv);
}
return r;
}
/* NOTE: returns a bool, 1 card matches, 0 it does not */
static int coolkey_match_card(sc_card_t *card)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
r = coolkey_select_applet(card);
return (r >= SC_SUCCESS);
}
static int coolkey_init(sc_card_t *card)
{
int r;
unsigned long flags;
unsigned long ext_flags;
coolkey_private_data_t * priv;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = coolkey_initialize(card);
if (r < 0) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD);
}
card->type = SC_CARD_TYPE_COOLKEY_GENERIC;
/* set Token Major/minor version */
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);
_sc_card_add_ec_alg(card, 384, flags, ext_flags, NULL);
_sc_card_add_ec_alg(card, 521, flags, ext_flags, NULL);
priv = COOLKEY_DATA(card);
if (priv->pin_count != 0) {
card->caps |= SC_CARD_CAP_ISO7816_PIN_INFO;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int
coolkey_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int r;
coolkey_private_data_t * priv = COOLKEY_DATA(card);
size_t rbuflen;
u8 *rbuf;
/* COOLKEY uses a separate pin from the card pin, managed by the applet.
* if we successfully log into coolkey, we will get a nonce, which we append
* to our APDUs to authenticate the apdu to the card. This allows coolkey to
* maintain separate per application login states without the application
* having to cache the pin */
switch (data->cmd) {
case SC_PIN_CMD_GET_INFO:
if (priv->nonce_valid) {
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
} else {
data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT;
/* coolkey retries is 100. It's unlikely the pin is block.
* instead, coolkey slows down the login command exponentially
*/
data->pin1.tries_left = 0xf;
}
if (tries_left) {
*tries_left = data->pin1.tries_left;
}
r = SC_SUCCESS;
break;
case SC_PIN_CMD_UNBLOCK:
case SC_PIN_CMD_CHANGE:
/* these 2 commands are currently reserved for TPS */
default:
r = SC_ERROR_NOT_SUPPORTED;
break;
case SC_PIN_CMD_VERIFY:
/* coolkey applet supports multiple pins, but TPS currently only uses one.
* just support the one pin for now (we need an array of nonces to handle
* multiple pins) */
/* coolkey only supports unpadded ascii pins, so no need to format the pin */
rbuflen = sizeof(priv->nonce);
rbuf = &priv->nonce[0];
r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_VERIFY_PIN,
data->pin_reference, 0, data->pin1.data, data->pin1.len,
&rbuf, &rbuflen, NULL, 0);
if (r < 0) {
break;
}
priv->nonce_valid = 1;
r = SC_SUCCESS;
}
return r;
}
static int
coolkey_logout(sc_card_t *card)
{
/* when we add multi pin support here, how do we know which pin to logout? */
coolkey_private_data_t * priv = COOLKEY_DATA(card);
u8 pin_ref = 0;
(void) coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_LOGOUT, pin_ref, 0, NULL, 0, NULL, NULL,
priv->nonce, sizeof(priv->nonce));
/* even if logout failed on the card, flush the nonce and clear the nonce_valid and we are effectively
* logged out... needing to login again to get a nonce back */
memset(priv->nonce, 0, sizeof(priv->nonce));
priv->nonce_valid = 0;
return SC_SUCCESS;
}
static int coolkey_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
r = coolkey_select_applet(card);
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_operations coolkey_ops;
static struct sc_card_driver coolkey_drv = {
"COOLKEY",
"coolkey",
&coolkey_ops,
NULL, 0, NULL
};
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
coolkey_ops = *iso_drv->ops;
coolkey_ops.match_card = coolkey_match_card;
coolkey_ops.init = coolkey_init;
coolkey_ops.finish = coolkey_finish;
coolkey_ops.select_file = coolkey_select_file; /* need to record object type */
coolkey_ops.get_challenge = coolkey_get_challenge;
coolkey_ops.read_binary = coolkey_read_binary;
coolkey_ops.write_binary = coolkey_write_binary;
coolkey_ops.set_security_env = coolkey_set_security_env;
coolkey_ops.restore_security_env = coolkey_restore_security_env;
coolkey_ops.compute_signature = coolkey_compute_crypt;
coolkey_ops.decipher = coolkey_compute_crypt;
coolkey_ops.card_ctl = coolkey_card_ctl;
coolkey_ops.check_sw = coolkey_check_sw;
coolkey_ops.pin_cmd = coolkey_pin_cmd;
coolkey_ops.logout = coolkey_logout;
coolkey_ops.card_reader_lock_obtained = coolkey_card_reader_lock_obtained;
return &coolkey_drv;
}
struct sc_card_driver * sc_get_coolkey_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_351_4 |
crossvul-cpp_data_good_4027_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP Security
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2014 Norbert Federa <norbert.federa@thincast.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 "security.h"
#include <freerdp/log.h>
#include <winpr/crypto.h>
#define TAG FREERDP_TAG("core")
/* 0x36 repeated 40 times */
static const BYTE pad1[40] = { "\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36"
"\x36\x36\x36\x36\x36\x36\x36\x36" };
/* 0x5C repeated 48 times */
static const BYTE pad2[48] = { "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C"
"\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" };
static const BYTE fips_reverse_table[256] = {
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
};
static const BYTE fips_oddparity_table[256] = {
0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0b, 0x0b, 0x0d, 0x0d, 0x0e, 0x0e,
0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16, 0x19, 0x19, 0x1a, 0x1a, 0x1c, 0x1c, 0x1f, 0x1f,
0x20, 0x20, 0x23, 0x23, 0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2a, 0x2a, 0x2c, 0x2c, 0x2f, 0x2f,
0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3b, 0x3b, 0x3d, 0x3d, 0x3e, 0x3e,
0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49, 0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f,
0x51, 0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5b, 0x5b, 0x5d, 0x5d, 0x5e, 0x5e,
0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6b, 0x6b, 0x6d, 0x6d, 0x6e, 0x6e,
0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76, 0x79, 0x79, 0x7a, 0x7a, 0x7c, 0x7c, 0x7f, 0x7f,
0x80, 0x80, 0x83, 0x83, 0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8a, 0x8a, 0x8c, 0x8c, 0x8f, 0x8f,
0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9b, 0x9b, 0x9d, 0x9d, 0x9e, 0x9e,
0xa1, 0xa1, 0xa2, 0xa2, 0xa4, 0xa4, 0xa7, 0xa7, 0xa8, 0xa8, 0xab, 0xab, 0xad, 0xad, 0xae, 0xae,
0xb0, 0xb0, 0xb3, 0xb3, 0xb5, 0xb5, 0xb6, 0xb6, 0xb9, 0xb9, 0xba, 0xba, 0xbc, 0xbc, 0xbf, 0xbf,
0xc1, 0xc1, 0xc2, 0xc2, 0xc4, 0xc4, 0xc7, 0xc7, 0xc8, 0xc8, 0xcb, 0xcb, 0xcd, 0xcd, 0xce, 0xce,
0xd0, 0xd0, 0xd3, 0xd3, 0xd5, 0xd5, 0xd6, 0xd6, 0xd9, 0xd9, 0xda, 0xda, 0xdc, 0xdc, 0xdf, 0xdf,
0xe0, 0xe0, 0xe3, 0xe3, 0xe5, 0xe5, 0xe6, 0xe6, 0xe9, 0xe9, 0xea, 0xea, 0xec, 0xec, 0xef, 0xef,
0xf1, 0xf1, 0xf2, 0xf2, 0xf4, 0xf4, 0xf7, 0xf7, 0xf8, 0xf8, 0xfb, 0xfb, 0xfd, 0xfd, 0xfe, 0xfe
};
static BOOL security_salted_hash(const BYTE* salt, const BYTE* input, int length, const BYTE* salt1,
const BYTE* salt2, BYTE* output)
{
WINPR_DIGEST_CTX* sha1 = NULL;
WINPR_DIGEST_CTX* md5 = NULL;
BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
BOOL result = FALSE;
/* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1(Input + Salt + Salt1 + Salt2)) */
/* SHA1_Digest = SHA1(Input + Salt + Salt1 + Salt2) */
if (!(sha1 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
goto out;
if (!winpr_Digest_Update(sha1, input, length)) /* Input */
goto out;
if (!winpr_Digest_Update(sha1, salt, 48)) /* Salt (48 bytes) */
goto out;
if (!winpr_Digest_Update(sha1, salt1, 32)) /* Salt1 (32 bytes) */
goto out;
if (!winpr_Digest_Update(sha1, salt2, 32)) /* Salt2 (32 bytes) */
goto out;
if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest)))
goto out;
/* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1_Digest) */
if (!(md5 = winpr_Digest_New()))
goto out;
/* Allow FIPS override for use of MD5 here, this is used for creating hashes of the
* premaster_secret and master_secret */
/* used for RDP licensing as described in MS-RDPELE. 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. */
if (!winpr_Digest_Init_Allow_FIPS(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, salt, 48)) /* Salt (48 bytes) */
goto out;
if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */
goto out;
if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH))
goto out;
result = TRUE;
out:
winpr_Digest_Free(sha1);
winpr_Digest_Free(md5);
return result;
}
static BOOL security_premaster_hash(const char* input, int length, const BYTE* premaster_secret,
const BYTE* client_random, const BYTE* server_random,
BYTE* output)
{
/* PremasterHash(Input) = SaltedHash(PremasterSecret, Input, ClientRandom, ServerRandom) */
return security_salted_hash(premaster_secret, (BYTE*)input, length, client_random,
server_random, output);
}
BOOL security_master_secret(const BYTE* premaster_secret, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* MasterSecret = PremasterHash('A') + PremasterHash('BB') + PremasterHash('CCC') */
return security_premaster_hash("A", 1, premaster_secret, client_random, server_random,
&output[0]) &&
security_premaster_hash("BB", 2, premaster_secret, client_random, server_random,
&output[16]) &&
security_premaster_hash("CCC", 3, premaster_secret, client_random, server_random,
&output[32]);
}
static BOOL security_master_hash(const char* input, int length, const BYTE* master_secret,
const BYTE* client_random, const BYTE* server_random, BYTE* output)
{
/* MasterHash(Input) = SaltedHash(MasterSecret, Input, ServerRandom, ClientRandom) */
return security_salted_hash(master_secret, (const BYTE*)input, length, server_random,
client_random, output);
}
BOOL security_session_key_blob(const BYTE* master_secret, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* MasterHash = MasterHash('A') + MasterHash('BB') + MasterHash('CCC') */
return security_master_hash("A", 1, master_secret, client_random, server_random, &output[0]) &&
security_master_hash("BB", 2, master_secret, client_random, server_random,
&output[16]) &&
security_master_hash("CCC", 3, master_secret, client_random, server_random, &output[32]);
}
void security_mac_salt_key(const BYTE* session_key_blob, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* MacSaltKey = First128Bits(SessionKeyBlob) */
memcpy(output, session_key_blob, 16);
}
static BOOL security_md5_16_32_32(const BYTE* in0, const BYTE* in1, const BYTE* in2, BYTE* output)
{
WINPR_DIGEST_CTX* md5 = NULL;
BOOL result = FALSE;
if (!(md5 = winpr_Digest_New()))
return FALSE;
if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, in0, 16))
goto out;
if (!winpr_Digest_Update(md5, in1, 32))
goto out;
if (!winpr_Digest_Update(md5, in2, 32))
goto out;
if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH))
goto out;
result = TRUE;
out:
winpr_Digest_Free(md5);
return result;
}
static BOOL security_md5_16_32_32_Allow_FIPS(const BYTE* in0, const BYTE* in1, const BYTE* in2,
BYTE* output)
{
WINPR_DIGEST_CTX* md5 = NULL;
BOOL result = FALSE;
if (!(md5 = winpr_Digest_New()))
return FALSE;
if (!winpr_Digest_Init_Allow_FIPS(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, in0, 16))
goto out;
if (!winpr_Digest_Update(md5, in1, 32))
goto out;
if (!winpr_Digest_Update(md5, in2, 32))
goto out;
if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH))
goto out;
result = TRUE;
out:
winpr_Digest_Free(md5);
return result;
}
BOOL security_licensing_encryption_key(const BYTE* session_key_blob, const BYTE* client_random,
const BYTE* server_random, BYTE* output)
{
/* LicensingEncryptionKey = MD5(Second128Bits(SessionKeyBlob) + ClientRandom + ServerRandom))
* Allow FIPS use of MD5 here, this is just used for creating the licensing encryption key as
* described in MS-RDPELE. 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 security_md5_16_32_32_Allow_FIPS(&session_key_blob[16], client_random, server_random,
output);
}
static void security_UINT32_le(BYTE* output, UINT32 value)
{
output[0] = (value)&0xFF;
output[1] = (value >> 8) & 0xFF;
output[2] = (value >> 16) & 0xFF;
output[3] = (value >> 24) & 0xFF;
}
BOOL security_mac_data(const BYTE* mac_salt_key, const BYTE* data, UINT32 length, BYTE* output)
{
WINPR_DIGEST_CTX* sha1 = NULL;
WINPR_DIGEST_CTX* md5 = NULL;
BYTE length_le[4];
BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
BOOL result = FALSE;
/* MacData = MD5(MacSaltKey + pad2 + SHA1(MacSaltKey + pad1 + length + data)) */
security_UINT32_le(length_le, length); /* length must be little-endian */
/* SHA1_Digest = SHA1(MacSaltKey + pad1 + length + data) */
if (!(sha1 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
goto out;
if (!winpr_Digest_Update(sha1, mac_salt_key, 16)) /* MacSaltKey */
goto out;
if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) /* pad1 */
goto out;
if (!winpr_Digest_Update(sha1, length_le, sizeof(length_le))) /* length */
goto out;
if (!winpr_Digest_Update(sha1, data, length)) /* data */
goto out;
if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest)))
goto out;
/* MacData = MD5(MacSaltKey + pad2 + SHA1_Digest) */
if (!(md5 = winpr_Digest_New()))
goto out;
/* Allow FIPS override for use of MD5 here, this is only used for creating the MACData field of
* the */
/* Client Platform Challenge Response packet (from MS-RDPELE section 2.2.2.5). 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. */
if (!winpr_Digest_Init_Allow_FIPS(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, mac_salt_key, 16)) /* MacSaltKey */
goto out;
if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) /* pad2 */
goto out;
if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */
goto out;
if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH))
goto out;
result = TRUE;
out:
winpr_Digest_Free(sha1);
winpr_Digest_Free(md5);
return result;
}
BOOL security_mac_signature(rdpRdp* rdp, const BYTE* data, UINT32 length, BYTE* output)
{
WINPR_DIGEST_CTX* sha1 = NULL;
WINPR_DIGEST_CTX* md5 = NULL;
BYTE length_le[4];
BYTE md5_digest[WINPR_MD5_DIGEST_LENGTH];
BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
BOOL result = FALSE;
security_UINT32_le(length_le, length); /* length must be little-endian */
/* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */
if (!(sha1 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
goto out;
if (!winpr_Digest_Update(sha1, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */
goto out;
if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) /* pad1 */
goto out;
if (!winpr_Digest_Update(sha1, length_le, sizeof(length_le))) /* length */
goto out;
if (!winpr_Digest_Update(sha1, data, length)) /* data */
goto out;
if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest)))
goto out;
/* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */
if (!(md5 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */
goto out;
if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) /* pad2 */
goto out;
if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */
goto out;
if (!winpr_Digest_Final(md5, md5_digest, sizeof(md5_digest)))
goto out;
memcpy(output, md5_digest, 8);
result = TRUE;
out:
winpr_Digest_Free(sha1);
winpr_Digest_Free(md5);
return result;
}
BOOL security_salted_mac_signature(rdpRdp* rdp, const BYTE* data, UINT32 length, BOOL encryption,
BYTE* output)
{
WINPR_DIGEST_CTX* sha1 = NULL;
WINPR_DIGEST_CTX* md5 = NULL;
BYTE length_le[4];
BYTE use_count_le[4];
BYTE md5_digest[WINPR_MD5_DIGEST_LENGTH];
BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH];
BOOL result = FALSE;
security_UINT32_le(length_le, length); /* length must be little-endian */
if (encryption)
{
security_UINT32_le(use_count_le, rdp->encrypt_checksum_use_count);
}
else
{
/*
* We calculate checksum on plain text, so we must have already
* decrypt it, which means decrypt_checksum_use_count is off by one.
*/
security_UINT32_le(use_count_le, rdp->decrypt_checksum_use_count - 1);
}
/* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */
if (!(sha1 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
goto out;
if (!winpr_Digest_Update(sha1, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */
goto out;
if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) /* pad1 */
goto out;
if (!winpr_Digest_Update(sha1, length_le, sizeof(length_le))) /* length */
goto out;
if (!winpr_Digest_Update(sha1, data, length)) /* data */
goto out;
if (!winpr_Digest_Update(sha1, use_count_le, sizeof(use_count_le))) /* encryptionCount */
goto out;
if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest)))
goto out;
/* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */
if (!(md5 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */
goto out;
if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) /* pad2 */
goto out;
if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */
goto out;
if (!winpr_Digest_Final(md5, md5_digest, sizeof(md5_digest)))
goto out;
memcpy(output, md5_digest, 8);
result = TRUE;
out:
winpr_Digest_Free(sha1);
winpr_Digest_Free(md5);
return result;
}
static BOOL security_A(BYTE* master_secret, const BYTE* client_random, BYTE* server_random,
BYTE* output)
{
return security_premaster_hash("A", 1, master_secret, client_random, server_random,
&output[0]) &&
security_premaster_hash("BB", 2, master_secret, client_random, server_random,
&output[16]) &&
security_premaster_hash("CCC", 3, master_secret, client_random, server_random,
&output[32]);
}
static BOOL security_X(BYTE* master_secret, const BYTE* client_random, BYTE* server_random,
BYTE* output)
{
return security_premaster_hash("X", 1, master_secret, client_random, server_random,
&output[0]) &&
security_premaster_hash("YY", 2, master_secret, client_random, server_random,
&output[16]) &&
security_premaster_hash("ZZZ", 3, master_secret, client_random, server_random,
&output[32]);
}
static void fips_expand_key_bits(BYTE* in, BYTE* out)
{
BYTE buf[21], c;
int i, b, p, r;
/* reverse every byte in the key */
for (i = 0; i < 21; i++)
buf[i] = fips_reverse_table[in[i]];
/* insert a zero-bit after every 7th bit */
for (i = 0, b = 0; i < 24; i++, b += 7)
{
p = b / 8;
r = b % 8;
if (r <= 1)
{
out[i] = (buf[p] << r) & 0xfe;
}
else
{
/* c is accumulator */
c = buf[p] << r;
c |= buf[p + 1] >> (8 - r);
out[i] = c & 0xfe;
}
}
/* reverse every byte */
/* alter lsb so the byte has odd parity */
for (i = 0; i < 24; i++)
out[i] = fips_oddparity_table[fips_reverse_table[out[i]]];
}
BOOL security_establish_keys(const BYTE* client_random, rdpRdp* rdp)
{
BYTE pre_master_secret[48];
BYTE master_secret[48];
BYTE session_key_blob[48];
BYTE* server_random;
BYTE salt[] = { 0xD1, 0x26, 0x9E }; /* 40 bits: 3 bytes, 56 bits: 1 byte */
rdpSettings* settings;
BOOL status;
settings = rdp->settings;
server_random = settings->ServerRandom;
if (settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
WINPR_DIGEST_CTX* sha1;
BYTE client_encrypt_key_t[WINPR_SHA1_DIGEST_LENGTH + 1];
BYTE client_decrypt_key_t[WINPR_SHA1_DIGEST_LENGTH + 1];
if (!(sha1 = winpr_Digest_New()))
return FALSE;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1) ||
!winpr_Digest_Update(sha1, client_random + 16, 16) ||
!winpr_Digest_Update(sha1, server_random + 16, 16) ||
!winpr_Digest_Final(sha1, client_encrypt_key_t, sizeof(client_encrypt_key_t)))
{
winpr_Digest_Free(sha1);
return FALSE;
}
client_encrypt_key_t[20] = client_encrypt_key_t[0];
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1) ||
!winpr_Digest_Update(sha1, client_random, 16) ||
!winpr_Digest_Update(sha1, server_random, 16) ||
!winpr_Digest_Final(sha1, client_decrypt_key_t, sizeof(client_decrypt_key_t)))
{
winpr_Digest_Free(sha1);
return FALSE;
}
client_decrypt_key_t[20] = client_decrypt_key_t[0];
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1) ||
!winpr_Digest_Update(sha1, client_decrypt_key_t, WINPR_SHA1_DIGEST_LENGTH) ||
!winpr_Digest_Update(sha1, client_encrypt_key_t, WINPR_SHA1_DIGEST_LENGTH) ||
!winpr_Digest_Final(sha1, rdp->fips_sign_key, WINPR_SHA1_DIGEST_LENGTH))
{
winpr_Digest_Free(sha1);
return FALSE;
}
winpr_Digest_Free(sha1);
if (rdp->settings->ServerMode)
{
fips_expand_key_bits(client_encrypt_key_t, rdp->fips_decrypt_key);
fips_expand_key_bits(client_decrypt_key_t, rdp->fips_encrypt_key);
}
else
{
fips_expand_key_bits(client_encrypt_key_t, rdp->fips_encrypt_key);
fips_expand_key_bits(client_decrypt_key_t, rdp->fips_decrypt_key);
}
}
memcpy(pre_master_secret, client_random, 24);
memcpy(pre_master_secret + 24, server_random, 24);
if (!security_A(pre_master_secret, client_random, server_random, master_secret) ||
!security_X(master_secret, client_random, server_random, session_key_blob))
{
return FALSE;
}
memcpy(rdp->sign_key, session_key_blob, 16);
if (rdp->settings->ServerMode)
{
status = security_md5_16_32_32(&session_key_blob[16], client_random, server_random,
rdp->encrypt_key);
status &= security_md5_16_32_32(&session_key_blob[32], client_random, server_random,
rdp->decrypt_key);
}
else
{
/* Allow FIPS use of MD5 here, this is just used for generation of the SessionKeyBlob as
* described in MS-RDPELE. */
/* 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. */
status = security_md5_16_32_32_Allow_FIPS(&session_key_blob[16], client_random,
server_random, rdp->decrypt_key);
status &= security_md5_16_32_32_Allow_FIPS(&session_key_blob[32], client_random,
server_random, rdp->encrypt_key);
}
if (!status)
return FALSE;
if (settings->EncryptionMethods == ENCRYPTION_METHOD_40BIT)
{
memcpy(rdp->sign_key, salt, 3);
memcpy(rdp->decrypt_key, salt, 3);
memcpy(rdp->encrypt_key, salt, 3);
rdp->rc4_key_len = 8;
}
else if (settings->EncryptionMethods == ENCRYPTION_METHOD_56BIT)
{
memcpy(rdp->sign_key, salt, 1);
memcpy(rdp->decrypt_key, salt, 1);
memcpy(rdp->encrypt_key, salt, 1);
rdp->rc4_key_len = 8;
}
else if (settings->EncryptionMethods == ENCRYPTION_METHOD_128BIT)
{
rdp->rc4_key_len = 16;
}
memcpy(rdp->decrypt_update_key, rdp->decrypt_key, 16);
memcpy(rdp->encrypt_update_key, rdp->encrypt_key, 16);
rdp->decrypt_use_count = 0;
rdp->decrypt_checksum_use_count = 0;
rdp->encrypt_use_count = 0;
rdp->encrypt_checksum_use_count = 0;
return TRUE;
}
static BOOL security_key_update(BYTE* key, BYTE* update_key, int key_len, rdpRdp* rdp)
{
BYTE sha1h[WINPR_SHA1_DIGEST_LENGTH];
WINPR_DIGEST_CTX* sha1 = NULL;
WINPR_DIGEST_CTX* md5 = NULL;
WINPR_RC4_CTX* rc4 = NULL;
BYTE salt[] = { 0xD1, 0x26, 0x9E }; /* 40 bits: 3 bytes, 56 bits: 1 byte */
BOOL result = FALSE;
WLog_DBG(TAG, "updating RDP key");
if (!(sha1 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1))
goto out;
if (!winpr_Digest_Update(sha1, update_key, key_len))
goto out;
if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1)))
goto out;
if (!winpr_Digest_Update(sha1, key, key_len))
goto out;
if (!winpr_Digest_Final(sha1, sha1h, sizeof(sha1h)))
goto out;
if (!(md5 = winpr_Digest_New()))
goto out;
if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
goto out;
if (!winpr_Digest_Update(md5, update_key, key_len))
goto out;
if (!winpr_Digest_Update(md5, pad2, sizeof(pad2)))
goto out;
if (!winpr_Digest_Update(md5, sha1h, sizeof(sha1h)))
goto out;
if (!winpr_Digest_Final(md5, key, WINPR_MD5_DIGEST_LENGTH))
goto out;
if (!(rc4 = winpr_RC4_New(key, key_len)))
goto out;
if (!winpr_RC4_Update(rc4, key_len, key, key))
goto out;
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_40BIT)
memcpy(key, salt, 3);
else if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_56BIT)
memcpy(key, salt, 1);
result = TRUE;
out:
winpr_Digest_Free(sha1);
winpr_Digest_Free(md5);
winpr_RC4_Free(rc4);
return result;
}
BOOL security_encrypt(BYTE* data, size_t length, rdpRdp* rdp)
{
BOOL rc = FALSE;
EnterCriticalSection(&rdp->critical);
if (rdp->encrypt_use_count >= 4096)
{
if (!security_key_update(rdp->encrypt_key, rdp->encrypt_update_key, rdp->rc4_key_len, rdp))
goto fail;
winpr_RC4_Free(rdp->rc4_encrypt_key);
rdp->rc4_encrypt_key = winpr_RC4_New(rdp->encrypt_key, rdp->rc4_key_len);
if (!rdp->rc4_encrypt_key)
goto fail;
rdp->encrypt_use_count = 0;
}
if (!winpr_RC4_Update(rdp->rc4_encrypt_key, length, data, data))
goto fail;
rdp->encrypt_use_count++;
rdp->encrypt_checksum_use_count++;
rc = TRUE;
fail:
LeaveCriticalSection(&rdp->critical);
return rc;
}
BOOL security_decrypt(BYTE* data, size_t length, rdpRdp* rdp)
{
if (rdp->rc4_decrypt_key == NULL)
return FALSE;
if (rdp->decrypt_use_count >= 4096)
{
if (!security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len, rdp))
return FALSE;
winpr_RC4_Free(rdp->rc4_decrypt_key);
rdp->rc4_decrypt_key = winpr_RC4_New(rdp->decrypt_key, rdp->rc4_key_len);
if (!rdp->rc4_decrypt_key)
return FALSE;
rdp->decrypt_use_count = 0;
}
if (!winpr_RC4_Update(rdp->rc4_decrypt_key, length, data, data))
return FALSE;
rdp->decrypt_use_count += 1;
rdp->decrypt_checksum_use_count++;
return TRUE;
}
BOOL security_hmac_signature(const BYTE* data, size_t length, BYTE* output, rdpRdp* rdp)
{
BYTE buf[WINPR_SHA1_DIGEST_LENGTH];
BYTE use_count_le[4];
WINPR_HMAC_CTX* hmac;
BOOL result = FALSE;
security_UINT32_le(use_count_le, rdp->encrypt_use_count);
if (!(hmac = winpr_HMAC_New()))
return FALSE;
if (!winpr_HMAC_Init(hmac, WINPR_MD_SHA1, rdp->fips_sign_key, WINPR_SHA1_DIGEST_LENGTH))
goto out;
if (!winpr_HMAC_Update(hmac, data, length))
goto out;
if (!winpr_HMAC_Update(hmac, use_count_le, 4))
goto out;
if (!winpr_HMAC_Final(hmac, buf, WINPR_SHA1_DIGEST_LENGTH))
goto out;
memmove(output, buf, 8);
result = TRUE;
out:
winpr_HMAC_Free(hmac);
return result;
}
BOOL security_fips_encrypt(BYTE* data, size_t length, rdpRdp* rdp)
{
BOOL rc = FALSE;
size_t olen;
EnterCriticalSection(&rdp->critical);
if (!winpr_Cipher_Update(rdp->fips_encrypt, data, length, data, &olen))
goto fail;
rdp->encrypt_use_count++;
rc = TRUE;
fail:
LeaveCriticalSection(&rdp->critical);
return rc;
}
BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp)
{
size_t olen;
if (!rdp || !rdp->fips_decrypt)
return FALSE;
if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen))
return FALSE;
return TRUE;
}
BOOL security_fips_check_signature(const BYTE* data, size_t length, const BYTE* sig, rdpRdp* rdp)
{
BYTE buf[WINPR_SHA1_DIGEST_LENGTH];
BYTE use_count_le[4];
WINPR_HMAC_CTX* hmac;
BOOL result = FALSE;
security_UINT32_le(use_count_le, rdp->decrypt_use_count);
if (!(hmac = winpr_HMAC_New()))
return FALSE;
if (!winpr_HMAC_Init(hmac, WINPR_MD_SHA1, rdp->fips_sign_key, WINPR_SHA1_DIGEST_LENGTH))
goto out;
if (!winpr_HMAC_Update(hmac, data, length))
goto out;
if (!winpr_HMAC_Update(hmac, use_count_le, 4))
goto out;
if (!winpr_HMAC_Final(hmac, buf, WINPR_SHA1_DIGEST_LENGTH))
goto out;
rdp->decrypt_use_count++;
if (!memcmp(sig, buf, 8))
result = TRUE;
out:
winpr_HMAC_Free(hmac);
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4027_0 |
crossvul-cpp_data_bad_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"
/*
* 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(8);
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 "));
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, "\n\t\t packet exceeded snapshot"));
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, "\n\t\t packet exceeded snapshot"));
return 0;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_259_0 |
crossvul-cpp_data_bad_5215_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE N N H H AAA N N CCCC EEEEE %
% E NN N H H A A NN N C E %
% EEE N N N HHHHH AAAAA N N N C EEE %
% E N NN H H A A N NN C E %
% EEEEE N N H H A A N N CCCC EEEEE %
% %
% %
% MagickCore Image Enhancement Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-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/accelerate-private.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o G a m m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoGammaImage() extract the 'mean' from the image and adjust the image
% to try make set its gamma appropriatally.
%
% The format of the AutoGammaImage method is:
%
% MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-level
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AutoGammaImage(Image *image,
ExceptionInfo *exception)
{
double
gamma,
log_mean,
mean,
sans;
MagickStatusType
status;
register ssize_t
i;
log_mean=log(0.5);
if (image->channel_mask == DefaultChannels)
{
/*
Apply gamma correction equally across all given channels.
*/
(void) GetImageMean(image,&mean,&sans,exception);
gamma=log(mean*QuantumScale)/log_mean;
return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception));
}
/*
Auto-gamma each channel separately.
*/
status=MagickTrue;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
ChannelType
channel_mask;
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
channel_mask=SetImageChannelMask(image,(ChannelType) (1 << i));
status=GetImageMean(image,&mean,&sans,exception);
gamma=log(mean*QuantumScale)/log_mean;
status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception);
(void) SetImageChannelMask(image,channel_mask);
if (status == MagickFalse)
break;
}
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o L e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoLevelImage() adjusts the levels of a particular image channel by
% scaling the minimum and maximum values to the full quantum range.
%
% The format of the LevelImage method is:
%
% MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-level
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType AutoLevelImage(Image *image,
ExceptionInfo *exception)
{
return(MinMaxStretchImage(image,0.0,0.0,1.0,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B r i g h t n e s s C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BrightnessContrastImage() changes the brightness and/or contrast of an
% image. It converts the brightness and contrast parameters into slope and
% intercept and calls a polynomical function to apply to the image.
%
% The format of the BrightnessContrastImage method is:
%
% MagickBooleanType BrightnessContrastImage(Image *image,
% const double brightness,const double contrast,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o brightness: the brightness percent (-100 .. 100).
%
% o contrast: the contrast percent (-100 .. 100).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BrightnessContrastImage(Image *image,
const double brightness,const double contrast,ExceptionInfo *exception)
{
#define BrightnessContastImageTag "BrightnessContast/Image"
double
alpha,
coefficients[2],
intercept,
slope;
MagickBooleanType
status;
/*
Compute slope and intercept.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
alpha=contrast;
slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0));
if (slope < 0.0)
slope=0.0;
intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope);
coefficients[0]=slope;
coefficients[1]=intercept;
status=FunctionImage(image,PolynomialFunction,2,coefficients,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l u t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClutImage() replaces each color value in the given image, by using it as an
% index to lookup a replacement color value in a Color Look UP Table in the
% form of an image. The values are extracted along a diagonal of the CLUT
% image so either a horizontal or vertial gradient image can be used.
%
% Typically this is used to either re-color a gray-scale image according to a
% color gradient in the CLUT image, or to perform a freeform histogram
% (level) adjustment according to the (typically gray-scale) gradient in the
% CLUT image.
%
% When the 'channel' mask includes the matte/alpha transparency channel but
% one image has no such channel it is assumed that that image is a simple
% gray-scale image that will effect the alpha channel values, either for
% gray-scale coloring (with transparent or semi-transparent colors), or
% a histogram adjustment of existing alpha channel values. If both images
% have matte channels, direct and normal indexing is applied, which is rarely
% used.
%
% The format of the ClutImage method is:
%
% MagickBooleanType ClutImage(Image *image,Image *clut_image,
% const PixelInterpolateMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image, which is replaced by indexed CLUT values
%
% o clut_image: the color lookup table image for replacement color values.
%
% o method: the pixel interpolation method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image,
const PixelInterpolateMethod method,ExceptionInfo *exception)
{
#define ClutImageTag "Clut/Image"
CacheView
*clut_view,
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
*clut_map;
register ssize_t
i;
ssize_t adjust,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clut_image != (Image *) NULL);
assert(clut_image->signature == MagickCoreSignature);
if( SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if( (IsGrayColorspace(image->colorspace) != MagickFalse) &&
(IsGrayColorspace(clut_image->colorspace) == MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace,exception);
clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map));
if (clut_map == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Clut image.
*/
status=MagickTrue;
progress=0;
adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1);
clut_view=AcquireVirtualCacheView(clut_image,exception);
for (i=0; i <= (ssize_t) MaxMap; i++)
{
GetPixelInfo(clut_image,clut_map+i);
(void) InterpolatePixelInfo(clut_image,clut_view,method,
(double) i*(clut_image->columns-adjust)/MaxMap,(double) i*
(clut_image->rows-adjust)/MaxMap,clut_map+i,exception);
}
clut_view=DestroyCacheView(clut_view);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
PixelTrait
traits;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
traits=GetPixelChannelTraits(image,RedPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.red))].red;
traits=GetPixelChannelTraits(image,GreenPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.green))].green;
traits=GetPixelChannelTraits(image,BluePixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.blue))].blue;
traits=GetPixelChannelTraits(image,BlackPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.black))].black;
traits=GetPixelChannelTraits(image,AlphaPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum(
pixel.alpha))].alpha;
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ClutImage)
#endif
proceed=SetImageProgress(image,ClutImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map);
if ((clut_image->alpha_trait != UndefinedPixelTrait) &&
((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0))
(void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o l o r D e c i s i o n L i s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ColorDecisionListImage() accepts a lightweight Color Correction Collection
% (CCC) file which solely contains one or more color corrections and applies
% the correction to the image. Here is a sample CCC file:
%
% <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2">
% <ColorCorrection id="cc03345">
% <SOPNode>
% <Slope> 0.9 1.2 0.5 </Slope>
% <Offset> 0.4 -0.5 0.6 </Offset>
% <Power> 1.0 0.8 1.5 </Power>
% </SOPNode>
% <SATNode>
% <Saturation> 0.85 </Saturation>
% </SATNode>
% </ColorCorrection>
% </ColorCorrectionCollection>
%
% which includes the slop, offset, and power for each of the RGB channels
% as well as the saturation.
%
% The format of the ColorDecisionListImage method is:
%
% MagickBooleanType ColorDecisionListImage(Image *image,
% const char *color_correction_collection,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o color_correction_collection: the color correction collection in XML.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ColorDecisionListImage(Image *image,
const char *color_correction_collection,ExceptionInfo *exception)
{
#define ColorDecisionListCorrectImageTag "ColorDecisionList/Image"
typedef struct _Correction
{
double
slope,
offset,
power;
} Correction;
typedef struct _ColorCorrection
{
Correction
red,
green,
blue;
double
saturation;
} ColorCorrection;
CacheView
*image_view;
char
token[MagickPathExtent];
ColorCorrection
color_correction;
const char
*content,
*p;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
*cdl_map;
register ssize_t
i;
ssize_t
y;
XMLTreeInfo
*cc,
*ccc,
*sat,
*sop;
/*
Allocate and initialize cdl maps.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (color_correction_collection == (const char *) NULL)
return(MagickFalse);
ccc=NewXMLTree((const char *) color_correction_collection,exception);
if (ccc == (XMLTreeInfo *) NULL)
return(MagickFalse);
cc=GetXMLTreeChild(ccc,"ColorCorrection");
if (cc == (XMLTreeInfo *) NULL)
{
ccc=DestroyXMLTree(ccc);
return(MagickFalse);
}
color_correction.red.slope=1.0;
color_correction.red.offset=0.0;
color_correction.red.power=1.0;
color_correction.green.slope=1.0;
color_correction.green.offset=0.0;
color_correction.green.power=1.0;
color_correction.blue.slope=1.0;
color_correction.blue.offset=0.0;
color_correction.blue.power=1.0;
color_correction.saturation=0.0;
sop=GetXMLTreeChild(cc,"SOPNode");
if (sop != (XMLTreeInfo *) NULL)
{
XMLTreeInfo
*offset,
*power,
*slope;
slope=GetXMLTreeChild(sop,"Slope");
if (slope != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(slope);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.slope=StringToDouble(token,(char **) NULL);
break;
}
case 1:
{
color_correction.green.slope=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.slope=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
offset=GetXMLTreeChild(sop,"Offset");
if (offset != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(offset);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.offset=StringToDouble(token,
(char **) NULL);
break;
}
case 1:
{
color_correction.green.offset=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.offset=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
power=GetXMLTreeChild(sop,"Power");
if (power != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(power);
p=(const char *) content;
for (i=0; (*p != '\0') && (i < 3); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
switch (i)
{
case 0:
{
color_correction.red.power=StringToDouble(token,(char **) NULL);
break;
}
case 1:
{
color_correction.green.power=StringToDouble(token,
(char **) NULL);
break;
}
case 2:
{
color_correction.blue.power=StringToDouble(token,
(char **) NULL);
break;
}
}
}
}
}
sat=GetXMLTreeChild(cc,"SATNode");
if (sat != (XMLTreeInfo *) NULL)
{
XMLTreeInfo
*saturation;
saturation=GetXMLTreeChild(sat,"Saturation");
if (saturation != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(saturation);
p=(const char *) content;
GetNextToken(p,&p,MagickPathExtent,token);
color_correction.saturation=StringToDouble(token,(char **) NULL);
}
}
ccc=DestroyXMLTree(ccc);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" Color Correction Collection:");
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.slope: %g",color_correction.red.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.offset: %g",color_correction.red.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.red.power: %g",color_correction.red.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.slope: %g",color_correction.green.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.offset: %g",color_correction.green.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.green.power: %g",color_correction.green.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.slope: %g",color_correction.blue.slope);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.offset: %g",color_correction.blue.offset);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.blue.power: %g",color_correction.blue.power);
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" color_correction.saturation: %g",color_correction.saturation);
}
cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map));
if (cdl_map == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
for (i=0; i <= (ssize_t) MaxMap; i++)
{
cdl_map[i].red=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.red.slope*i/MaxMap+
color_correction.red.offset,color_correction.red.power))));
cdl_map[i].green=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.green.slope*i/MaxMap+
color_correction.green.offset,color_correction.green.power))));
cdl_map[i].blue=(double) ScaleMapToQuantum((double)
(MaxMap*(pow(color_correction.blue.slope*i/MaxMap+
color_correction.blue.offset,color_correction.blue.power))));
}
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Apply transfer function to colormap.
*/
double
luma;
luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+
0.07217f*image->colormap[i].blue;
image->colormap[i].red=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma;
image->colormap[i].green=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma;
image->colormap[i].blue=luma+color_correction.saturation*cdl_map[
ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma;
}
/*
Apply transfer function to image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
luma;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+
0.07217f*GetPixelBlue(image,q);
SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q);
SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q);
SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation*
(cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ColorDecisionListImageChannel)
#endif
proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag,
progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContrastImage() enhances the intensity differences between the lighter and
% darker elements of the image. Set sharpen to a MagickTrue to increase the
% image contrast otherwise the contrast is reduced.
%
% The format of the ContrastImage method is:
%
% MagickBooleanType ContrastImage(Image *image,
% const MagickBooleanType sharpen,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o sharpen: Increase or decrease image contrast.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void Contrast(const int sign,double *red,double *green,double *blue)
{
double
brightness,
hue,
saturation;
/*
Enhance contrast: dark color become darker, light color become lighter.
*/
assert(red != (double *) NULL);
assert(green != (double *) NULL);
assert(blue != (double *) NULL);
hue=0.0;
saturation=0.0;
brightness=0.0;
ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)-
brightness);
if (brightness > 1.0)
brightness=1.0;
else
if (brightness < 0.0)
brightness=0.0;
ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
}
MagickExport MagickBooleanType ContrastImage(Image *image,
const MagickBooleanType sharpen,ExceptionInfo *exception)
{
#define ContrastImageTag "Contrast/Image"
CacheView
*image_view;
int
sign;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
sign=sharpen != MagickFalse ? 1 : -1;
if (image->storage_class == PseudoClass)
{
/*
Contrast enhance colormap.
*/
for (i=0; i < (ssize_t) image->colors; i++)
{
double
blue,
green,
red;
red=(double) image->colormap[i].red;
green=(double) image->colormap[i].green;
blue=(double) image->colormap[i].blue;
Contrast(sign,&red,&green,&blue);
image->colormap[i].red=(MagickRealType) red;
image->colormap[i].green=(MagickRealType) green;
image->colormap[i].blue=(MagickRealType) blue;
}
}
/*
Contrast enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
red;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
Contrast(sign,&red,&green,&blue);
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ContrastImage)
#endif
proceed=SetImageProgress(image,ContrastImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n t r a s t S t r e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContrastStretchImage() is a simple image enhancement technique that attempts
% to improve the contrast in an image by 'stretching' the range of intensity
% values it contains to span a desired range of values. It differs from the
% more sophisticated histogram equalization in that it can only apply a
% linear scaling function to the image pixel values. As a result the
% 'enhancement' is less harsh.
%
% The format of the ContrastStretchImage method is:
%
% MagickBooleanType ContrastStretchImage(Image *image,
% const char *levels,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: the black point.
%
% o white_point: the white point.
%
% o levels: Specify the levels where the black and white points have the
% range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ContrastStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))
#define ContrastStretchImageTag "ContrastStretch/Image"
CacheView
*image_view;
double
*black,
*histogram,
*stretch_map,
*white;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate histogram and stretch map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black));
white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,
GetPixelChannels(image)*sizeof(*stretch_map));
if ((black == (double *) NULL) || (white == (double *) NULL) ||
(histogram == (double *) NULL) || (stretch_map == (double *) NULL))
{
if (stretch_map != (double *) NULL)
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (white != (double *) NULL)
white=(double *) RelinquishMagickMemory(white);
if (black != (double *) NULL)
black=(double *) RelinquishMagickMemory(black);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
pixel=GetPixelIntensity(image,p);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
if (image->channel_mask != DefaultChannels)
pixel=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(pixel))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black/white levels.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
black[i]=0.0;
white[i]=MaxRange(QuantumRange);
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > black_point)
break;
}
black[i]=(double) j;
intensity=0.0;
for (j=(ssize_t) MaxMap; j != 0; j--)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > ((double) image->columns*image->rows-white_point))
break;
}
white[i]=(double) j;
}
histogram=(double *) RelinquishMagickMemory(histogram);
/*
Stretch the histogram to create the stretched image mapping.
*/
(void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*stretch_map));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
gamma;
gamma=PerceptibleReciprocal(white[i]-black[i]);
if (j < (ssize_t) black[i])
stretch_map[GetPixelChannels(image)*j+i]=0.0;
else
if (j > (ssize_t) white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;
else
stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(
(double) (MaxMap*gamma*(j-black[i])));
}
}
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Stretch-contrast colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,RedPixelChannel);
image->colormap[j].red=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,GreenPixelChannel);
image->colormap[j].green=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,BluePixelChannel);
image->colormap[j].blue=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,AlphaPixelChannel);
image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];
}
}
}
/*
Stretch-contrast image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ContrastStretchImage)
#endif
proceed=SetImageProgress(image,ContrastStretchImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
white=(double *) RelinquishMagickMemory(white);
black=(double *) RelinquishMagickMemory(black);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E n h a n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EnhanceImage() applies a digital filter that improves the quality of a
% noisy image.
%
% The format of the EnhanceImage method is:
%
% Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
{
#define EnhanceImageTag "Enhance/Image"
#define EnhancePixel(weight) \
mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
distance_squared=(4.0+mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
distance_squared+=(7.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
distance_squared+=(5.0-mean)*distance*distance; \
if (distance_squared < 0.069) \
{ \
aggregate.red+=(weight)*GetPixelRed(image,r); \
aggregate.green+=(weight)*GetPixelGreen(image,r); \
aggregate.blue+=(weight)*GetPixelBlue(image,r); \
aggregate.black+=(weight)*GetPixelBlack(image,r); \
aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \
total_weight+=(weight); \
} \
r+=GetPixelChannels(image);
CacheView
*enhance_view,
*image_view;
Image
*enhance_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize enhanced image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
enhance_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (enhance_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
{
enhance_image=DestroyImage(enhance_image);
return((Image *) NULL);
}
/*
Enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,enhance_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2);
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
distance,
distance_squared,
mean,
total_weight;
PixelInfo
aggregate;
register const Quantum
*magick_restrict r;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(enhance_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(enhance_image);
continue;
}
GetPixelInfo(image,&aggregate);
total_weight=0.0;
GetPixelInfoPixel(image,p+center,&pixel);
r=p;
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
r=p+GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+2*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
EnhancePixel(40.0); EnhancePixel(10.0);
r=p+3*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+4*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
SetPixelViaPixelInfo(image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(enhance_image);
}
if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_EnhanceImage)
#endif
proceed=SetImageProgress(image,EnhanceImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
enhance_view=DestroyCacheView(enhance_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
enhance_image=DestroyImage(enhance_image);
return(enhance_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E q u a l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EqualizeImage() applies a histogram equalization to the image.
%
% The format of the EqualizeImage method is:
%
% MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType EqualizeImage(Image *image,
ExceptionInfo *exception)
{
#define EqualizeImageTag "Equalize/Image"
CacheView
*image_view;
double
black[CompositePixelChannel+1],
*equalize_map,
*histogram,
*map,
white[CompositePixelChannel+1];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize histogram arrays.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateEqualizeImage(image,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,
GetPixelChannels(image)*sizeof(*equalize_map));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*map));
if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) ||
(map == (double *) NULL))
{
if (map != (double *) NULL)
map=(double *) RelinquishMagickMemory(map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (equalize_map != (double *) NULL)
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
intensity=p[i];
if ((image->channel_mask & SyncChannels) != 0)
intensity=GetPixelIntensity(image,p);
histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Integrate the histogram to get the equalization map.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
map[GetPixelChannels(image)*j+i]=intensity;
}
}
(void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*equalize_map));
(void) ResetMagickMemory(black,0,sizeof(*black));
(void) ResetMagickMemory(white,0,sizeof(*white));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
black[i]=map[i];
white[i]=map[GetPixelChannels(image)*MaxMap+i];
if (black[i] != white[i])
for (j=0; j <= (ssize_t) MaxMap; j++)
equalize_map[GetPixelChannels(image)*j+i]=(double)
ScaleMapToQuantum((double) ((MaxMap*(map[
GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i])));
}
histogram=(double *) RelinquishMagickMemory(histogram);
map=(double *) RelinquishMagickMemory(map);
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Equalize colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].red=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+
channel];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,
GreenPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].green=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+
channel];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel);
if (black[channel] != white[channel])
image->colormap[j].blue=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+
channel];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,
AlphaPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].alpha=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+
channel];
}
}
}
/*
Equalize image.
*/
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j]))
continue;
q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_EqualizeImage)
#endif
proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G a m m a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GammaImage() gamma-corrects a particular image channel. The same
% image viewed on different devices will have perceptual differences in the
% way the image's intensities are represented on the screen. Specify
% individual gamma levels for the red, green, and blue channels, or adjust
% all three with the gamma parameter. Values typically range from 0.8 to 2.3.
%
% You can also reduce the influence of a particular channel with a gamma
% value of 0.
%
% The format of the GammaImage method is:
%
% MagickBooleanType GammaImage(Image *image,const double gamma,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o level: the image gamma as a string (e.g. 1.6,1.2,1.0).
%
% o gamma: the image gamma.
%
*/
static inline double gamma_pow(const double value,const double gamma)
{
return(value < 0.0 ? value : pow(value,gamma));
}
MagickExport MagickBooleanType GammaImage(Image *image,const double gamma,
ExceptionInfo *exception)
{
#define GammaCorrectImageTag "GammaCorrect/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
Quantum
*gamma_map;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize gamma maps.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (gamma == 1.0)
return(MagickTrue);
gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map));
if (gamma_map == (Quantum *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) ResetMagickMemory(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map));
if (gamma != 0.0)
for (i=0; i <= (ssize_t) MaxMap; i++)
gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/
MaxMap,1.0/gamma)));
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Gamma-correct colormap.
*/
#if !defined(MAGICKCORE_HDRI_SUPPORT)
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].red))];
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].green))];
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].blue))];
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap(
ClampToQuantum(image->colormap[i].alpha))];
#else
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=QuantumRange*gamma_pow(QuantumScale*
image->colormap[i].red,1.0/gamma);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=QuantumRange*gamma_pow(QuantumScale*
image->colormap[i].green,1.0/gamma);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=QuantumRange*gamma_pow(QuantumScale*
image->colormap[i].blue,1.0/gamma);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=QuantumRange*gamma_pow(QuantumScale*
image->colormap[i].alpha,1.0/gamma);
#endif
}
/*
Gamma-correct image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
#if !defined(MAGICKCORE_HDRI_SUPPORT)
q[j]=gamma_map[ScaleQuantumToMap(q[j])];
#else
q[j]=QuantumRange*gamma_pow(QuantumScale*q[j],1.0/gamma);
#endif
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GammaImage)
#endif
proceed=SetImageProgress(image,GammaCorrectImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map);
if (image->gamma != 0.0)
image->gamma*=gamma;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G r a y s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GrayscaleImage() converts the image to grayscale.
%
% The format of the GrayscaleImage method is:
%
% MagickBooleanType GrayscaleImage(Image *image,
% const PixelIntensityMethod method ,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o method: the pixel intensity method.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GrayscaleImage(Image *image,
const PixelIntensityMethod method,ExceptionInfo *exception)
{
#define GrayscaleImageTag "Grayscale/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
if (SyncImage(image,exception) == MagickFalse)
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse)
{
image->intensity=method;
image->type=GrayscaleType;
return(SetImageColorspace(image,GRAYColorspace,exception));
}
#endif
/*
Grayscale image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
blue,
green,
red,
intensity;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
red=(MagickRealType) GetPixelRed(image,q);
green=(MagickRealType) GetPixelGreen(image,q);
blue=(MagickRealType) GetPixelBlue(image,q);
intensity=0.0;
switch (method)
{
case AveragePixelIntensityMethod:
{
intensity=(red+green+blue)/3.0;
break;
}
case BrightnessPixelIntensityMethod:
{
intensity=MagickMax(MagickMax(red,green),blue);
break;
}
case LightnessPixelIntensityMethod:
{
intensity=(MagickMin(MagickMin(red,green),blue)+
MagickMax(MagickMax(red,green),blue))/2.0;
break;
}
case MSPixelIntensityMethod:
{
intensity=(MagickRealType) (((double) red*red+green*green+
blue*blue)/3.0);
break;
}
case Rec601LumaPixelIntensityMethod:
{
if (image->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec601LuminancePixelIntensityMethod:
{
if (image->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec709LumaPixelIntensityMethod:
default:
{
if (image->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case Rec709LuminancePixelIntensityMethod:
{
if (image->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case RMSPixelIntensityMethod:
{
intensity=(MagickRealType) (sqrt((double) red*red+green*green+
blue*blue)/sqrt(3.0));
break;
}
}
SetPixelGray(image,ClampToQuantum(intensity),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GrayscaleImage)
#endif
proceed=SetImageProgress(image,GrayscaleImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
image->intensity=method;
image->type=GrayscaleType;
return(SetImageColorspace(image,GRAYColorspace,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H a l d C l u t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% HaldClutImage() applies a Hald color lookup table to the image. A Hald
% color lookup table is a 3-dimensional color cube mapped to 2 dimensions.
% Create it with the HALD coder. You can apply any color transformation to
% the Hald image and then use this method to apply the transform to the
% image.
%
% The format of the HaldClutImage method is:
%
% MagickBooleanType HaldClutImage(Image *image,Image *hald_image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image, which is replaced by indexed CLUT values
%
% o hald_image: the color lookup table image for replacement color values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType HaldClutImage(Image *image,
const Image *hald_image,ExceptionInfo *exception)
{
#define HaldClutImageTag "Clut/Image"
typedef struct _HaldInfo
{
double
x,
y,
z;
} HaldInfo;
CacheView
*hald_view,
*image_view;
double
width;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
size_t
cube_size,
length,
level;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(hald_image != (Image *) NULL);
assert(hald_image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Hald clut image.
*/
status=MagickTrue;
progress=0;
length=(size_t) MagickMin((MagickRealType) hald_image->columns,
(MagickRealType) hald_image->rows);
for (level=2; (level*level*level) < length; level++) ;
level*=level;
cube_size=level*level;
width=(double) hald_image->columns;
GetPixelInfo(hald_image,&zero);
hald_view=AcquireVirtualCacheView(hald_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
offset;
HaldInfo
point;
PixelInfo
pixel,
pixel1,
pixel2,
pixel3,
pixel4;
point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q);
point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q);
point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q);
offset=point.x+level*floor(point.y)+cube_size*floor(point.z);
point.x-=floor(point.x);
point.y-=floor(point.y);
point.z-=floor(point.z);
pixel1=zero;
(void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset,width),floor(offset/width),&pixel1,exception);
pixel2=zero;
(void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
pixel3=zero;
CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
point.y,&pixel3);
offset+=cube_size;
(void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset,width),floor(offset/width),&pixel1,exception);
(void) InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
pixel4=zero;
CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
point.y,&pixel4);
pixel=zero;
CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha,
point.z,&pixel);
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
SetPixelRed(image,ClampToQuantum(pixel.red),q);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelBlack(image,ClampToQuantum(pixel.black),q);
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_HaldClutImage)
#endif
proceed=SetImageProgress(image,HaldClutImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
hald_view=DestroyCacheView(hald_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelImage() adjusts the levels of a particular image channel by
% scaling the colors falling between specified white and black points to
% the full available quantum range.
%
% The parameters provided represent the black, and white points. The black
% point specifies the darkest color in the image. Colors darker than the
% black point are set to zero. White point specifies the lightest color in
% the image. Colors brighter than the white point are set to the maximum
% quantum value.
%
% If a '!' flag is given, map black and white colors to the given levels
% rather than mapping those levels to black and white. See
% LevelizeImage() below.
%
% Gamma specifies a gamma correction to apply to the image.
%
% The format of the LevelImage method is:
%
% MagickBooleanType LevelImage(Image *image,const double black_point,
% const double white_point,const double gamma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: The level to map zero (black) to.
%
% o white_point: The level to map QuantumRange (white) to.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double LevelPixel(const double black_point,
const double white_point,const double gamma,const double pixel)
{
double
level_pixel,
scale;
if (fabs(white_point-black_point) < MagickEpsilon)
return(pixel);
scale=1.0/(white_point-black_point);
level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point),
1.0/gamma);
return(level_pixel);
}
MagickExport MagickBooleanType LevelImage(Image *image,const double black_point,
const double white_point,const double gamma,ExceptionInfo *exception)
{
#define LevelImageTag "Level/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Level colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].red));
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].green));
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].blue));
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point,
white_point,gamma,image->colormap[i].alpha));
}
/*
Level image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma,
(double) q[j]));
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_LevelImage)
#endif
proceed=SetImageProgress(image,LevelImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) ClampImage(image,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelizeImage() applies the reversed LevelImage() operation to just
% the specific channels specified. It compresses the full range of color
% values, so that they lie between the given black and white points. Gamma is
% applied before the values are mapped.
%
% LevelizeImage() can be called with by using a +level command line
% API option, or using a '!' on a -level or LevelImage() geometry string.
%
% It can be used to de-contrast a greyscale image to the exact levels
% specified. Or by using specific levels for each channel of an image you
% can convert a gray-scale image to any linear color gradient, according to
% those levels.
%
% The format of the LevelizeImage method is:
%
% MagickBooleanType LevelizeImage(Image *image,const double black_point,
% const double white_point,const double gamma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: The level to map zero (black) to.
%
% o white_point: The level to map QuantumRange (white) to.
%
% o gamma: adjust gamma by this factor before mapping values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LevelizeImage(Image *image,
const double black_point,const double white_point,const double gamma,
ExceptionInfo *exception)
{
#define LevelizeImageTag "Levelize/Image"
#define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \
(QuantumScale*(x)),gamma))*(white_point-black_point)+black_point)
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Level colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double) LevelizeValue(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double) LevelizeValue(
image->colormap[i].alpha);
}
/*
Level image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=LevelizeValue(q[j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_LevelizeImage)
#endif
proceed=SetImageProgress(image,LevelizeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L e v e l I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LevelImageColors() maps the given color to "black" and "white" values,
% linearly spreading out the colors, and level values on a channel by channel
% bases, as per LevelImage(). The given colors allows you to specify
% different level ranges for each of the color channels separately.
%
% If the boolean 'invert' is set true the image values will modifyed in the
% reverse direction. That is any existing "black" and "white" colors in the
% image will become the color values given, with all other values compressed
% appropriatally. This effectivally maps a greyscale gradient into the given
% color gradient.
%
% The format of the LevelImageColors method is:
%
% MagickBooleanType LevelImageColors(Image *image,
% const PixelInfo *black_color,const PixelInfo *white_color,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_color: The color to map black to/from
%
% o white_point: The color to map white to/from
%
% o invert: if true map the colors (levelize), rather than from (level)
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LevelImageColors(Image *image,
const PixelInfo *black_color,const PixelInfo *white_color,
const MagickBooleanType invert,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickStatusType
status;
/*
Allocate and initialize levels map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsGrayColorspace(black_color->colorspace) == MagickFalse) ||
(IsGrayColorspace(white_color->colorspace) == MagickFalse)))
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
if (invert == MagickFalse)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,RedChannel);
status&=LevelImage(image,black_color->red,white_color->red,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,GreenChannel);
status&=LevelImage(image,black_color->green,white_color->green,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,BlueChannel);
status&=LevelImage(image,black_color->blue,white_color->blue,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_mask=SetImageChannelMask(image,BlackChannel);
status&=LevelImage(image,black_color->black,white_color->black,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
{
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
}
else
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,RedChannel);
status&=LevelizeImage(image,black_color->red,white_color->red,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,GreenChannel);
status&=LevelizeImage(image,black_color->green,white_color->green,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
channel_mask=SetImageChannelMask(image,BlueChannel);
status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_mask=SetImageChannelMask(image,BlackChannel);
status&=LevelizeImage(image,black_color->black,white_color->black,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait != UndefinedPixelTrait))
{
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0,
exception);
(void) SetImageChannelMask(image,channel_mask);
}
}
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i n e a r S t r e t c h I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LinearStretchImage() discards any pixels below the black point and above
% the white point and levels the remaining pixels.
%
% The format of the LinearStretchImage method is:
%
% MagickBooleanType LinearStretchImage(Image *image,
% const double black_point,const double white_point,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o black_point: the black point.
%
% o white_point: the white point.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType LinearStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define LinearStretchImageTag "LinearStretch/Image"
CacheView
*image_view;
double
*histogram,
intensity;
MagickBooleanType
status;
ssize_t
black,
white,
y;
/*
Allocate histogram and linear map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Form histogram.
*/
(void) ResetMagickMemory(histogram,0,(MaxMap+1)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=GetPixelIntensity(image,p);
histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black and white point levels.
*/
intensity=0.0;
for (black=0; black < (ssize_t) MaxMap; black++)
{
intensity+=histogram[black];
if (intensity >= black_point)
break;
}
intensity=0.0;
for (white=(ssize_t) MaxMap; white != 0; white--)
{
intensity+=histogram[white];
if (intensity >= white_point)
break;
}
histogram=(double *) RelinquishMagickMemory(histogram);
status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black),
(double) ScaleMapToQuantum((MagickRealType) white),1.0,exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d u l a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModulateImage() lets you control the brightness, saturation, and hue
% of an image. Modulate represents the brightness, saturation, and hue
% as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the
% modulation is lightness, saturation, and hue. For HWB, use blackness,
% whiteness, and hue. And for HCL, use chrome, luma, and hue.
%
% The format of the ModulateImage method is:
%
% MagickBooleanType ModulateImage(Image *image,const char *modulate,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulate: Define the percent change in brightness, saturation, and hue.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void ModulateHCL(const double percent_hue,
const double percent_chroma,const double percent_luma,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue > 1.0)
hue-=1.0;
chroma*=0.01*percent_chroma;
luma*=0.01*percent_luma;
ConvertHCLToRGB(hue,chroma,luma,red,green,blue);
}
static inline void ModulateHCLp(const double percent_hue,
const double percent_chroma,const double percent_luma,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue > 1.0)
hue-=1.0;
chroma*=0.01*percent_chroma;
luma*=0.01*percent_luma;
ConvertHCLpToRGB(hue,chroma,luma,red,green,blue);
}
static inline void ModulateHSB(const double percent_hue,
const double percent_saturation,const double percent_brightness,double *red,
double *green,double *blue)
{
double
brightness,
hue,
saturation;
/*
Increase or decrease color brightness, saturation, or hue.
*/
ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue > 1.0)
hue-=1.0;
saturation*=0.01*percent_saturation;
brightness*=0.01*percent_brightness;
ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
}
static inline void ModulateHSI(const double percent_hue,
const double percent_saturation,const double percent_intensity,double *red,
double *green,double *blue)
{
double
intensity,
hue,
saturation;
/*
Increase or decrease color intensity, saturation, or hue.
*/
ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue > 1.0)
hue-=1.0;
saturation*=0.01*percent_saturation;
intensity*=0.01*percent_intensity;
ConvertHSIToRGB(hue,saturation,intensity,red,green,blue);
}
static inline void ModulateHSL(const double percent_hue,
const double percent_saturation,const double percent_lightness,double *red,
double *green,double *blue)
{
double
hue,
lightness,
saturation;
/*
Increase or decrease color lightness, saturation, or hue.
*/
ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue >= 1.0)
hue-=1.0;
saturation*=0.01*percent_saturation;
lightness*=0.01*percent_lightness;
ConvertHSLToRGB(hue,saturation,lightness,red,green,blue);
}
static inline void ModulateHSV(const double percent_hue,
const double percent_saturation,const double percent_value,double *red,
double *green,double *blue)
{
double
hue,
saturation,
value;
/*
Increase or decrease color value, saturation, or hue.
*/
ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue >= 1.0)
hue-=1.0;
saturation*=0.01*percent_saturation;
value*=0.01*percent_value;
ConvertHSVToRGB(hue,saturation,value,red,green,blue);
}
static inline void ModulateHWB(const double percent_hue,
const double percent_whiteness,const double percent_blackness,double *red,
double *green,double *blue)
{
double
blackness,
hue,
whiteness;
/*
Increase or decrease color blackness, whiteness, or hue.
*/
ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness);
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue >= 1.0)
hue-=1.0;
blackness*=0.01*percent_blackness;
whiteness*=0.01*percent_whiteness;
ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue);
}
static inline void ModulateLCHab(const double percent_luma,
const double percent_chroma,const double percent_hue,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue);
luma*=0.01*percent_luma;
chroma*=0.01*percent_chroma;
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue >= 1.0)
hue-=1.0;
ConvertLCHabToRGB(luma,chroma,hue,red,green,blue);
}
static inline void ModulateLCHuv(const double percent_luma,
const double percent_chroma,const double percent_hue,double *red,
double *green,double *blue)
{
double
hue,
luma,
chroma;
/*
Increase or decrease color luma, chroma, or hue.
*/
ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue);
luma*=0.01*percent_luma;
chroma*=0.01*percent_chroma;
hue+=0.5*(0.01*percent_hue-1.0);
while (hue < 0.0)
hue+=1.0;
while (hue >= 1.0)
hue-=1.0;
ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue);
}
MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate,
ExceptionInfo *exception)
{
#define ModulateImageTag "Modulate/Image"
CacheView
*image_view;
ColorspaceType
colorspace;
const char
*artifact;
double
percent_brightness,
percent_hue,
percent_saturation;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickStatusType
flags;
register ssize_t
i;
ssize_t
y;
/*
Initialize modulate table.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (modulate == (char *) NULL)
return(MagickFalse);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
flags=ParseGeometry(modulate,&geometry_info);
percent_brightness=geometry_info.rho;
percent_saturation=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
percent_saturation=100.0;
percent_hue=geometry_info.xi;
if ((flags & XiValue) == 0)
percent_hue=100.0;
colorspace=UndefinedColorspace;
artifact=GetImageArtifact(image,"modulate:colorspace");
if (artifact != (const char *) NULL)
colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions,
MagickFalse,artifact);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
double
blue,
green,
red;
/*
Modulate image colormap.
*/
red=(double) image->colormap[i].red;
green=(double) image->colormap[i].green;
blue=(double) image->colormap[i].blue;
switch (colorspace)
{
case HCLColorspace:
{
ModulateHCL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSBColorspace:
{
ModulateHSB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSIColorspace:
{
ModulateHSI(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSLColorspace:
default:
{
ModulateHSL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSVColorspace:
{
ModulateHSV(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HWBColorspace:
{
ModulateHWB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHabColorspace:
{
ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
case LCHuvColorspace:
{
ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
}
image->colormap[i].red=red;
image->colormap[i].green=green;
image->colormap[i].blue=blue;
}
/*
Modulate image.
*/
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateModulateImage(image,percent_brightness,percent_hue,
percent_saturation,colorspace,exception) != MagickFalse)
return(MagickTrue);
#endif
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
blue,
green,
red;
red=(double) GetPixelRed(image,q);
green=(double) GetPixelGreen(image,q);
blue=(double) GetPixelBlue(image,q);
switch (colorspace)
{
case HCLColorspace:
{
ModulateHCL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HCLpColorspace:
{
ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSBColorspace:
{
ModulateHSB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSLColorspace:
default:
{
ModulateHSL(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HSVColorspace:
{
ModulateHSV(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case HWBColorspace:
{
ModulateHWB(percent_hue,percent_saturation,percent_brightness,
&red,&green,&blue);
break;
}
case LCHabColorspace:
{
ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
case LCHColorspace:
case LCHuvColorspace:
{
ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
&red,&green,&blue);
break;
}
}
SetPixelRed(image,ClampToQuantum(red),q);
SetPixelGreen(image,ClampToQuantum(green),q);
SetPixelBlue(image,ClampToQuantum(blue),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ModulateImage)
#endif
proceed=SetImageProgress(image,ModulateImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e g a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NegateImage() negates the colors in the reference image. The grayscale
% option means that only grayscale values within the image are negated.
%
% The format of the NegateImage method is:
%
% MagickBooleanType NegateImage(Image *image,
% const MagickBooleanType grayscale,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o grayscale: If MagickTrue, only negate grayscale pixels within the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType NegateImage(Image *image,
const MagickBooleanType grayscale,ExceptionInfo *exception)
{
#define NegateImageTag "Negate/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Negate colormap.
*/
if( grayscale != MagickFalse )
if ((image->colormap[i].red != image->colormap[i].green) ||
(image->colormap[i].green != image->colormap[i].blue))
continue;
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=QuantumRange-image->colormap[i].red;
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=QuantumRange-image->colormap[i].green;
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=QuantumRange-image->colormap[i].blue;
}
/*
Negate image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
if( grayscale != MagickFalse )
{
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if ((GetPixelReadMask(image,q) == 0) ||
IsPixelGray(image,q) != MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=QuantumRange-q[j];
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_NegateImage)
#endif
proceed=SetImageProgress(image,NegateImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(MagickTrue);
}
/*
Negate image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[j]=QuantumRange-q[j];
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_NegateImage)
#endif
proceed=SetImageProgress(image,NegateImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N o r m a l i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The NormalizeImage() method enhances the contrast of a color image by
% mapping the darkest 2 percent of all pixel to black and the brightest
% 1 percent to white.
%
% The format of the NormalizeImage method is:
%
% MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType NormalizeImage(Image *image,
ExceptionInfo *exception)
{
double
black_point,
white_point;
black_point=(double) image->columns*image->rows*0.0015;
white_point=(double) image->columns*image->rows*0.9995;
return(ContrastStretchImage(image,black_point,white_point,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S i g m o i d a l C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SigmoidalContrastImage() adjusts the contrast of an image with a non-linear
% sigmoidal contrast algorithm. Increase the contrast of the image using a
% sigmoidal transfer function without saturating highlights or shadows.
% Contrast indicates how much to increase the contrast (0 is none; 3 is
% typical; 20 is pushing it); mid-point indicates where midtones fall in the
% resultant image (0 is white; 50% is middle-gray; 100% is black). Set
% sharpen to MagickTrue to increase the image contrast otherwise the contrast
% is reduced.
%
% The format of the SigmoidalContrastImage method is:
%
% MagickBooleanType SigmoidalContrastImage(Image *image,
% const MagickBooleanType sharpen,const char *levels,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o sharpen: Increase or decrease image contrast.
%
% o contrast: strength of the contrast, the larger the number the more
% 'threshold-like' it becomes.
%
% o midpoint: midpoint of the function as a color value 0 to QuantumRange.
%
% o exception: return any errors or warnings in this structure.
%
*/
/*
ImageMagick 6 has a version of this function which uses LUTs.
*/
/*
Sigmoidal function Sigmoidal with inflexion point moved to b and "slope
constant" set to a.
The first version, based on the hyperbolic tangent tanh, when combined with
the scaling step, is an exact arithmetic clone of the the sigmoid function
based on the logistic curve. The equivalence is based on the identity
1/(1+exp(-t)) = (1+tanh(t/2))/2
(http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the
scaled sigmoidal derivation is invariant under affine transformations of
the ordinate.
The tanh version is almost certainly more accurate and cheaper. The 0.5
factor in the argument is to clone the legacy ImageMagick behavior. The
reason for making the define depend on atanh even though it only uses tanh
has to do with the construction of the inverse of the scaled sigmoidal.
*/
#if defined(MAGICKCORE_HAVE_ATANH)
#define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) )
#else
#define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) )
#endif
/*
Scaled sigmoidal function:
( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) /
( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) )
See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and
http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit
of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by
zero. This is fixed below by exiting immediately when contrast is small,
leaving the image (or colormap) unmodified. This appears to be safe because
the series expansion of the logistic sigmoidal function around x=b is
1/2-a*(b-x)/4+...
so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh).
*/
#define ScaledSigmoidal(a,b,x) ( \
(Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \
(Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) )
/*
Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b
may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic
sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even
when creating a LUT from in gamut values, hence the branching. In
addition, HDRI may have out of gamut values.
InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal:
It is only a right inverse. This is unavoidable.
*/
static inline double InverseScaledSigmoidal(const double a,const double b,
const double x)
{
const double sig0=Sigmoidal(a,b,0.0);
const double sig1=Sigmoidal(a,b,1.0);
const double argument=(sig1-sig0)*x+sig0;
const double clamped=
(
#if defined(MAGICKCORE_HAVE_ATANH)
argument < -1+MagickEpsilon
?
-1+MagickEpsilon
:
( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
);
return(b+(2.0/a)*atanh(clamped));
#else
argument < MagickEpsilon
?
MagickEpsilon
:
( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
);
return(b-log(1.0/clamped-1.0)/a);
#endif
}
MagickExport MagickBooleanType SigmoidalContrastImage(Image *image,
const MagickBooleanType sharpen,const double contrast,const double midpoint,
ExceptionInfo *exception)
{
#define SigmoidalContrastImageTag "SigmoidalContrast/Image"
#define ScaledSig(x) ( ClampToQuantum(QuantumRange* \
ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) )
#define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \
InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) )
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Convenience macros.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
/*
Side effect: may clamp values unless contrast<MagickEpsilon, in which
case nothing is done.
*/
if (contrast < MagickEpsilon)
return(MagickTrue);
/*
Sigmoidal-contrast enhance colormap.
*/
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
if( sharpen != MagickFalse )
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(MagickRealType) ScaledSig(
image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(MagickRealType) ScaledSig(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(MagickRealType) ScaledSig(
image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(MagickRealType) ScaledSig(
image->colormap[i].alpha);
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(MagickRealType) InverseScaledSig(
image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(MagickRealType) InverseScaledSig(
image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(MagickRealType) InverseScaledSig(
image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(MagickRealType) InverseScaledSig(
image->colormap[i].alpha);
}
}
/*
Sigmoidal-contrast enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if( sharpen != MagickFalse )
q[i]=ScaledSig(q[i]);
else
q[i]=InverseScaledSig(q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SigmoidalContrastImage)
#endif
proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5215_1 |
crossvul-cpp_data_bad_5271_0 | /* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2015 */
#ifdef CAPSTONE_HAS_X86
#include <string.h>
#include <stdlib.h>
#include "X86Mapping.h"
#include "X86DisassemblerDecoder.h"
#include "../../utils.h"
uint64_t arch_masks[9] = {
0, 0xff,
0xffff,
0,
0xffffffff,
0, 0, 0,
0xffffffffffffffffLL
};
static x86_reg sib_base_map[] = {
X86_REG_INVALID,
#define ENTRY(x) X86_REG_##x,
ALL_SIB_BASES
#undef ENTRY
};
// Fill-ins to make the compiler happy. These constants are never actually
// assigned; they are just filler to make an automatically-generated switch
// statement work.
enum {
X86_REG_BX_SI = 500,
X86_REG_BX_DI = 501,
X86_REG_BP_SI = 502,
X86_REG_BP_DI = 503,
X86_REG_sib = 504,
X86_REG_sib64 = 505
};
static x86_reg sib_index_map[] = {
X86_REG_INVALID,
#define ENTRY(x) X86_REG_##x,
ALL_EA_BASES
REGS_XMM
REGS_YMM
REGS_ZMM
#undef ENTRY
};
static x86_reg segment_map[] = {
X86_REG_INVALID,
X86_REG_CS,
X86_REG_SS,
X86_REG_DS,
X86_REG_ES,
X86_REG_FS,
X86_REG_GS,
};
x86_reg x86_map_sib_base(int r)
{
return sib_base_map[r];
}
x86_reg x86_map_sib_index(int r)
{
return sib_index_map[r];
}
x86_reg x86_map_segment(int r)
{
return segment_map[r];
}
#ifndef CAPSTONE_DIET
static name_map reg_name_maps[] = {
{ X86_REG_INVALID, NULL },
{ X86_REG_AH, "ah" },
{ X86_REG_AL, "al" },
{ X86_REG_AX, "ax" },
{ X86_REG_BH, "bh" },
{ X86_REG_BL, "bl" },
{ X86_REG_BP, "bp" },
{ X86_REG_BPL, "bpl" },
{ X86_REG_BX, "bx" },
{ X86_REG_CH, "ch" },
{ X86_REG_CL, "cl" },
{ X86_REG_CS, "cs" },
{ X86_REG_CX, "cx" },
{ X86_REG_DH, "dh" },
{ X86_REG_DI, "di" },
{ X86_REG_DIL, "dil" },
{ X86_REG_DL, "dl" },
{ X86_REG_DS, "ds" },
{ X86_REG_DX, "dx" },
{ X86_REG_EAX, "eax" },
{ X86_REG_EBP, "ebp" },
{ X86_REG_EBX, "ebx" },
{ X86_REG_ECX, "ecx" },
{ X86_REG_EDI, "edi" },
{ X86_REG_EDX, "edx" },
{ X86_REG_EFLAGS, "flags" },
{ X86_REG_EIP, "eip" },
{ X86_REG_EIZ, "eiz" },
{ X86_REG_ES, "es" },
{ X86_REG_ESI, "esi" },
{ X86_REG_ESP, "esp" },
{ X86_REG_FPSW, "fpsw" },
{ X86_REG_FS, "fs" },
{ X86_REG_GS, "gs" },
{ X86_REG_IP, "ip" },
{ X86_REG_RAX, "rax" },
{ X86_REG_RBP, "rbp" },
{ X86_REG_RBX, "rbx" },
{ X86_REG_RCX, "rcx" },
{ X86_REG_RDI, "rdi" },
{ X86_REG_RDX, "rdx" },
{ X86_REG_RIP, "rip" },
{ X86_REG_RIZ, "riz" },
{ X86_REG_RSI, "rsi" },
{ X86_REG_RSP, "rsp" },
{ X86_REG_SI, "si" },
{ X86_REG_SIL, "sil" },
{ X86_REG_SP, "sp" },
{ X86_REG_SPL, "spl" },
{ X86_REG_SS, "ss" },
{ X86_REG_CR0, "cr0" },
{ X86_REG_CR1, "cr1" },
{ X86_REG_CR2, "cr2" },
{ X86_REG_CR3, "cr3" },
{ X86_REG_CR4, "cr4" },
{ X86_REG_CR5, "cr5" },
{ X86_REG_CR6, "cr6" },
{ X86_REG_CR7, "cr7" },
{ X86_REG_CR8, "cr8" },
{ X86_REG_CR9, "cr9" },
{ X86_REG_CR10, "cr10" },
{ X86_REG_CR11, "cr11" },
{ X86_REG_CR12, "cr12" },
{ X86_REG_CR13, "cr13" },
{ X86_REG_CR14, "cr14" },
{ X86_REG_CR15, "cr15" },
{ X86_REG_DR0, "dr0" },
{ X86_REG_DR1, "dr1" },
{ X86_REG_DR2, "dr2" },
{ X86_REG_DR3, "dr3" },
{ X86_REG_DR4, "dr4" },
{ X86_REG_DR5, "dr5" },
{ X86_REG_DR6, "dr6" },
{ X86_REG_DR7, "dr7" },
{ X86_REG_DR8, "dr8" },
{ X86_REG_DR9, "dr9" },
{ X86_REG_DR10, "dr10" },
{ X86_REG_DR11, "dr11" },
{ X86_REG_DR12, "dr12" },
{ X86_REG_DR13, "dr13" },
{ X86_REG_DR14, "dr14" },
{ X86_REG_DR15, "dr15" },
{ X86_REG_FP0, "fp0" },
{ X86_REG_FP1, "fp1" },
{ X86_REG_FP2, "fp2" },
{ X86_REG_FP3, "fp3" },
{ X86_REG_FP4, "fp4" },
{ X86_REG_FP5, "fp5" },
{ X86_REG_FP6, "fp6" },
{ X86_REG_FP7, "fp7" },
{ X86_REG_K0, "k0" },
{ X86_REG_K1, "k1" },
{ X86_REG_K2, "k2" },
{ X86_REG_K3, "k3" },
{ X86_REG_K4, "k4" },
{ X86_REG_K5, "k5" },
{ X86_REG_K6, "k6" },
{ X86_REG_K7, "k7" },
{ X86_REG_MM0, "mm0" },
{ X86_REG_MM1, "mm1" },
{ X86_REG_MM2, "mm2" },
{ X86_REG_MM3, "mm3" },
{ X86_REG_MM4, "mm4" },
{ X86_REG_MM5, "mm5" },
{ X86_REG_MM6, "mm6" },
{ X86_REG_MM7, "mm7" },
{ X86_REG_R8, "r8" },
{ X86_REG_R9, "r9" },
{ X86_REG_R10, "r10" },
{ X86_REG_R11, "r11" },
{ X86_REG_R12, "r12" },
{ X86_REG_R13, "r13" },
{ X86_REG_R14, "r14" },
{ X86_REG_R15, "r15" },
{ X86_REG_ST0, "st0" },
{ X86_REG_ST1, "st1" },
{ X86_REG_ST2, "st2" },
{ X86_REG_ST3, "st3" },
{ X86_REG_ST4, "st4" },
{ X86_REG_ST5, "st5" },
{ X86_REG_ST6, "st6" },
{ X86_REG_ST7, "st7" },
{ X86_REG_XMM0, "xmm0" },
{ X86_REG_XMM1, "xmm1" },
{ X86_REG_XMM2, "xmm2" },
{ X86_REG_XMM3, "xmm3" },
{ X86_REG_XMM4, "xmm4" },
{ X86_REG_XMM5, "xmm5" },
{ X86_REG_XMM6, "xmm6" },
{ X86_REG_XMM7, "xmm7" },
{ X86_REG_XMM8, "xmm8" },
{ X86_REG_XMM9, "xmm9" },
{ X86_REG_XMM10, "xmm10" },
{ X86_REG_XMM11, "xmm11" },
{ X86_REG_XMM12, "xmm12" },
{ X86_REG_XMM13, "xmm13" },
{ X86_REG_XMM14, "xmm14" },
{ X86_REG_XMM15, "xmm15" },
{ X86_REG_XMM16, "xmm16" },
{ X86_REG_XMM17, "xmm17" },
{ X86_REG_XMM18, "xmm18" },
{ X86_REG_XMM19, "xmm19" },
{ X86_REG_XMM20, "xmm20" },
{ X86_REG_XMM21, "xmm21" },
{ X86_REG_XMM22, "xmm22" },
{ X86_REG_XMM23, "xmm23" },
{ X86_REG_XMM24, "xmm24" },
{ X86_REG_XMM25, "xmm25" },
{ X86_REG_XMM26, "xmm26" },
{ X86_REG_XMM27, "xmm27" },
{ X86_REG_XMM28, "xmm28" },
{ X86_REG_XMM29, "xmm29" },
{ X86_REG_XMM30, "xmm30" },
{ X86_REG_XMM31, "xmm31" },
{ X86_REG_YMM0, "ymm0" },
{ X86_REG_YMM1, "ymm1" },
{ X86_REG_YMM2, "ymm2" },
{ X86_REG_YMM3, "ymm3" },
{ X86_REG_YMM4, "ymm4" },
{ X86_REG_YMM5, "ymm5" },
{ X86_REG_YMM6, "ymm6" },
{ X86_REG_YMM7, "ymm7" },
{ X86_REG_YMM8, "ymm8" },
{ X86_REG_YMM9, "ymm9" },
{ X86_REG_YMM10, "ymm10" },
{ X86_REG_YMM11, "ymm11" },
{ X86_REG_YMM12, "ymm12" },
{ X86_REG_YMM13, "ymm13" },
{ X86_REG_YMM14, "ymm14" },
{ X86_REG_YMM15, "ymm15" },
{ X86_REG_YMM16, "ymm16" },
{ X86_REG_YMM17, "ymm17" },
{ X86_REG_YMM18, "ymm18" },
{ X86_REG_YMM19, "ymm19" },
{ X86_REG_YMM20, "ymm20" },
{ X86_REG_YMM21, "ymm21" },
{ X86_REG_YMM22, "ymm22" },
{ X86_REG_YMM23, "ymm23" },
{ X86_REG_YMM24, "ymm24" },
{ X86_REG_YMM25, "ymm25" },
{ X86_REG_YMM26, "ymm26" },
{ X86_REG_YMM27, "ymm27" },
{ X86_REG_YMM28, "ymm28" },
{ X86_REG_YMM29, "ymm29" },
{ X86_REG_YMM30, "ymm30" },
{ X86_REG_YMM31, "ymm31" },
{ X86_REG_ZMM0, "zmm0" },
{ X86_REG_ZMM1, "zmm1" },
{ X86_REG_ZMM2, "zmm2" },
{ X86_REG_ZMM3, "zmm3" },
{ X86_REG_ZMM4, "zmm4" },
{ X86_REG_ZMM5, "zmm5" },
{ X86_REG_ZMM6, "zmm6" },
{ X86_REG_ZMM7, "zmm7" },
{ X86_REG_ZMM8, "zmm8" },
{ X86_REG_ZMM9, "zmm9" },
{ X86_REG_ZMM10, "zmm10" },
{ X86_REG_ZMM11, "zmm11" },
{ X86_REG_ZMM12, "zmm12" },
{ X86_REG_ZMM13, "zmm13" },
{ X86_REG_ZMM14, "zmm14" },
{ X86_REG_ZMM15, "zmm15" },
{ X86_REG_ZMM16, "zmm16" },
{ X86_REG_ZMM17, "zmm17" },
{ X86_REG_ZMM18, "zmm18" },
{ X86_REG_ZMM19, "zmm19" },
{ X86_REG_ZMM20, "zmm20" },
{ X86_REG_ZMM21, "zmm21" },
{ X86_REG_ZMM22, "zmm22" },
{ X86_REG_ZMM23, "zmm23" },
{ X86_REG_ZMM24, "zmm24" },
{ X86_REG_ZMM25, "zmm25" },
{ X86_REG_ZMM26, "zmm26" },
{ X86_REG_ZMM27, "zmm27" },
{ X86_REG_ZMM28, "zmm28" },
{ X86_REG_ZMM29, "zmm29" },
{ X86_REG_ZMM30, "zmm30" },
{ X86_REG_ZMM31, "zmm31" },
{ X86_REG_R8B, "r8b" },
{ X86_REG_R9B, "r9b" },
{ X86_REG_R10B, "r10b" },
{ X86_REG_R11B, "r11b" },
{ X86_REG_R12B, "r12b" },
{ X86_REG_R13B, "r13b" },
{ X86_REG_R14B, "r14b" },
{ X86_REG_R15B, "r15b" },
{ X86_REG_R8D, "r8d" },
{ X86_REG_R9D, "r9d" },
{ X86_REG_R10D, "r10d" },
{ X86_REG_R11D, "r11d" },
{ X86_REG_R12D, "r12d" },
{ X86_REG_R13D, "r13d" },
{ X86_REG_R14D, "r14d" },
{ X86_REG_R15D, "r15d" },
{ X86_REG_R8W, "r8w" },
{ X86_REG_R9W, "r9w" },
{ X86_REG_R10W, "r10w" },
{ X86_REG_R11W, "r11w" },
{ X86_REG_R12W, "r12w" },
{ X86_REG_R13W, "r13w" },
{ X86_REG_R14W, "r14w" },
{ X86_REG_R15W, "r15w" },
};
#endif
// register size in non-64bit mode
uint8_t regsize_map_32 [] = {
0, // { X86_REG_INVALID, NULL },
1, // { X86_REG_AH, "ah" },
1, // { X86_REG_AL, "al" },
2, // { X86_REG_AX, "ax" },
1, // { X86_REG_BH, "bh" },
1, // { X86_REG_BL, "bl" },
2, // { X86_REG_BP, "bp" },
1, // { X86_REG_BPL, "bpl" },
2, // { X86_REG_BX, "bx" },
1, // { X86_REG_CH, "ch" },
1, // { X86_REG_CL, "cl" },
2, // { X86_REG_CS, "cs" },
2, // { X86_REG_CX, "cx" },
1, // { X86_REG_DH, "dh" },
2, // { X86_REG_DI, "di" },
1, // { X86_REG_DIL, "dil" },
1, // { X86_REG_DL, "dl" },
2, // { X86_REG_DS, "ds" },
2, // { X86_REG_DX, "dx" },
4, // { X86_REG_EAX, "eax" },
4, // { X86_REG_EBP, "ebp" },
4, // { X86_REG_EBX, "ebx" },
4, // { X86_REG_ECX, "ecx" },
4, // { X86_REG_EDI, "edi" },
4, // { X86_REG_EDX, "edx" },
4, // { X86_REG_EFLAGS, "flags" },
4, // { X86_REG_EIP, "eip" },
4, // { X86_REG_EIZ, "eiz" },
2, // { X86_REG_ES, "es" },
4, // { X86_REG_ESI, "esi" },
4, // { X86_REG_ESP, "esp" },
10, // { X86_REG_FPSW, "fpsw" },
2, // { X86_REG_FS, "fs" },
2, // { X86_REG_GS, "gs" },
2, // { X86_REG_IP, "ip" },
8, // { X86_REG_RAX, "rax" },
8, // { X86_REG_RBP, "rbp" },
8, // { X86_REG_RBX, "rbx" },
8, // { X86_REG_RCX, "rcx" },
8, // { X86_REG_RDI, "rdi" },
8, // { X86_REG_RDX, "rdx" },
8, // { X86_REG_RIP, "rip" },
8, // { X86_REG_RIZ, "riz" },
8, // { X86_REG_RSI, "rsi" },
8, // { X86_REG_RSP, "rsp" },
2, // { X86_REG_SI, "si" },
1, // { X86_REG_SIL, "sil" },
2, // { X86_REG_SP, "sp" },
1, // { X86_REG_SPL, "spl" },
2, // { X86_REG_SS, "ss" },
4, // { X86_REG_CR0, "cr0" },
4, // { X86_REG_CR1, "cr1" },
4, // { X86_REG_CR2, "cr2" },
4, // { X86_REG_CR3, "cr3" },
4, // { X86_REG_CR4, "cr4" },
8, // { X86_REG_CR5, "cr5" },
8, // { X86_REG_CR6, "cr6" },
8, // { X86_REG_CR7, "cr7" },
8, // { X86_REG_CR8, "cr8" },
8, // { X86_REG_CR9, "cr9" },
8, // { X86_REG_CR10, "cr10" },
8, // { X86_REG_CR11, "cr11" },
8, // { X86_REG_CR12, "cr12" },
8, // { X86_REG_CR13, "cr13" },
8, // { X86_REG_CR14, "cr14" },
8, // { X86_REG_CR15, "cr15" },
4, // { X86_REG_DR0, "dr0" },
4, // { X86_REG_DR1, "dr1" },
4, // { X86_REG_DR2, "dr2" },
4, // { X86_REG_DR3, "dr3" },
4, // { X86_REG_DR4, "dr4" },
4, // { X86_REG_DR5, "dr5" },
4, // { X86_REG_DR6, "dr6" },
4, // { X86_REG_DR7, "dr7" },
4, // { X86_REG_DR8, "dr8" },
4, // { X86_REG_DR9, "dr9" },
4, // { X86_REG_DR10, "dr10" },
4, // { X86_REG_DR11, "dr11" },
4, // { X86_REG_DR12, "dr12" },
4, // { X86_REG_DR13, "dr13" },
4, // { X86_REG_DR14, "dr14" },
4, // { X86_REG_DR15, "dr15" },
10, // { X86_REG_FP0, "fp0" },
10, // { X86_REG_FP1, "fp1" },
10, // { X86_REG_FP2, "fp2" },
10, // { X86_REG_FP3, "fp3" },
10, // { X86_REG_FP4, "fp4" },
10, // { X86_REG_FP5, "fp5" },
10, // { X86_REG_FP6, "fp6" },
10, // { X86_REG_FP7, "fp7" },
2, // { X86_REG_K0, "k0" },
2, // { X86_REG_K1, "k1" },
2, // { X86_REG_K2, "k2" },
2, // { X86_REG_K3, "k3" },
2, // { X86_REG_K4, "k4" },
2, // { X86_REG_K5, "k5" },
2, // { X86_REG_K6, "k6" },
2, // { X86_REG_K7, "k7" },
8, // { X86_REG_MM0, "mm0" },
8, // { X86_REG_MM1, "mm1" },
8, // { X86_REG_MM2, "mm2" },
8, // { X86_REG_MM3, "mm3" },
8, // { X86_REG_MM4, "mm4" },
8, // { X86_REG_MM5, "mm5" },
8, // { X86_REG_MM6, "mm6" },
8, // { X86_REG_MM7, "mm7" },
8, // { X86_REG_R8, "r8" },
8, // { X86_REG_R9, "r9" },
8, // { X86_REG_R10, "r10" },
8, // { X86_REG_R11, "r11" },
8, // { X86_REG_R12, "r12" },
8, // { X86_REG_R13, "r13" },
8, // { X86_REG_R14, "r14" },
8, // { X86_REG_R15, "r15" },
10, // { X86_REG_ST0, "st0" },
10, // { X86_REG_ST1, "st1" },
10, // { X86_REG_ST2, "st2" },
10, // { X86_REG_ST3, "st3" },
10, // { X86_REG_ST4, "st4" },
10, // { X86_REG_ST5, "st5" },
10, // { X86_REG_ST6, "st6" },
10, // { X86_REG_ST7, "st7" },
16, // { X86_REG_XMM0, "xmm0" },
16, // { X86_REG_XMM1, "xmm1" },
16, // { X86_REG_XMM2, "xmm2" },
16, // { X86_REG_XMM3, "xmm3" },
16, // { X86_REG_XMM4, "xmm4" },
16, // { X86_REG_XMM5, "xmm5" },
16, // { X86_REG_XMM6, "xmm6" },
16, // { X86_REG_XMM7, "xmm7" },
16, // { X86_REG_XMM8, "xmm8" },
16, // { X86_REG_XMM9, "xmm9" },
16, // { X86_REG_XMM10, "xmm10" },
16, // { X86_REG_XMM11, "xmm11" },
16, // { X86_REG_XMM12, "xmm12" },
16, // { X86_REG_XMM13, "xmm13" },
16, // { X86_REG_XMM14, "xmm14" },
16, // { X86_REG_XMM15, "xmm15" },
16, // { X86_REG_XMM16, "xmm16" },
16, // { X86_REG_XMM17, "xmm17" },
16, // { X86_REG_XMM18, "xmm18" },
16, // { X86_REG_XMM19, "xmm19" },
16, // { X86_REG_XMM20, "xmm20" },
16, // { X86_REG_XMM21, "xmm21" },
16, // { X86_REG_XMM22, "xmm22" },
16, // { X86_REG_XMM23, "xmm23" },
16, // { X86_REG_XMM24, "xmm24" },
16, // { X86_REG_XMM25, "xmm25" },
16, // { X86_REG_XMM26, "xmm26" },
16, // { X86_REG_XMM27, "xmm27" },
16, // { X86_REG_XMM28, "xmm28" },
16, // { X86_REG_XMM29, "xmm29" },
16, // { X86_REG_XMM30, "xmm30" },
16, // { X86_REG_XMM31, "xmm31" },
32, // { X86_REG_YMM0, "ymm0" },
32, // { X86_REG_YMM1, "ymm1" },
32, // { X86_REG_YMM2, "ymm2" },
32, // { X86_REG_YMM3, "ymm3" },
32, // { X86_REG_YMM4, "ymm4" },
32, // { X86_REG_YMM5, "ymm5" },
32, // { X86_REG_YMM6, "ymm6" },
32, // { X86_REG_YMM7, "ymm7" },
32, // { X86_REG_YMM8, "ymm8" },
32, // { X86_REG_YMM9, "ymm9" },
32, // { X86_REG_YMM10, "ymm10" },
32, // { X86_REG_YMM11, "ymm11" },
32, // { X86_REG_YMM12, "ymm12" },
32, // { X86_REG_YMM13, "ymm13" },
32, // { X86_REG_YMM14, "ymm14" },
32, // { X86_REG_YMM15, "ymm15" },
32, // { X86_REG_YMM16, "ymm16" },
32, // { X86_REG_YMM17, "ymm17" },
32, // { X86_REG_YMM18, "ymm18" },
32, // { X86_REG_YMM19, "ymm19" },
32, // { X86_REG_YMM20, "ymm20" },
32, // { X86_REG_YMM21, "ymm21" },
32, // { X86_REG_YMM22, "ymm22" },
32, // { X86_REG_YMM23, "ymm23" },
32, // { X86_REG_YMM24, "ymm24" },
32, // { X86_REG_YMM25, "ymm25" },
32, // { X86_REG_YMM26, "ymm26" },
32, // { X86_REG_YMM27, "ymm27" },
32, // { X86_REG_YMM28, "ymm28" },
32, // { X86_REG_YMM29, "ymm29" },
32, // { X86_REG_YMM30, "ymm30" },
32, // { X86_REG_YMM31, "ymm31" },
64, // { X86_REG_ZMM0, "zmm0" },
64, // { X86_REG_ZMM1, "zmm1" },
64, // { X86_REG_ZMM2, "zmm2" },
64, // { X86_REG_ZMM3, "zmm3" },
64, // { X86_REG_ZMM4, "zmm4" },
64, // { X86_REG_ZMM5, "zmm5" },
64, // { X86_REG_ZMM6, "zmm6" },
64, // { X86_REG_ZMM7, "zmm7" },
64, // { X86_REG_ZMM8, "zmm8" },
64, // { X86_REG_ZMM9, "zmm9" },
64, // { X86_REG_ZMM10, "zmm10" },
64, // { X86_REG_ZMM11, "zmm11" },
64, // { X86_REG_ZMM12, "zmm12" },
64, // { X86_REG_ZMM13, "zmm13" },
64, // { X86_REG_ZMM14, "zmm14" },
64, // { X86_REG_ZMM15, "zmm15" },
64, // { X86_REG_ZMM16, "zmm16" },
64, // { X86_REG_ZMM17, "zmm17" },
64, // { X86_REG_ZMM18, "zmm18" },
64, // { X86_REG_ZMM19, "zmm19" },
64, // { X86_REG_ZMM20, "zmm20" },
64, // { X86_REG_ZMM21, "zmm21" },
64, // { X86_REG_ZMM22, "zmm22" },
64, // { X86_REG_ZMM23, "zmm23" },
64, // { X86_REG_ZMM24, "zmm24" },
64, // { X86_REG_ZMM25, "zmm25" },
64, // { X86_REG_ZMM26, "zmm26" },
64, // { X86_REG_ZMM27, "zmm27" },
64, // { X86_REG_ZMM28, "zmm28" },
64, // { X86_REG_ZMM29, "zmm29" },
64, // { X86_REG_ZMM30, "zmm30" },
64, // { X86_REG_ZMM31, "zmm31" },
1, // { X86_REG_R8B, "r8b" },
1, // { X86_REG_R9B, "r9b" },
1, // { X86_REG_R10B, "r10b" },
1, // { X86_REG_R11B, "r11b" },
1, // { X86_REG_R12B, "r12b" },
1, // { X86_REG_R13B, "r13b" },
1, // { X86_REG_R14B, "r14b" },
1, // { X86_REG_R15B, "r15b" },
4, // { X86_REG_R8D, "r8d" },
4, // { X86_REG_R9D, "r9d" },
4, // { X86_REG_R10D, "r10d" },
4, // { X86_REG_R11D, "r11d" },
4, // { X86_REG_R12D, "r12d" },
4, // { X86_REG_R13D, "r13d" },
4, // { X86_REG_R14D, "r14d" },
4, // { X86_REG_R15D, "r15d" },
2, // { X86_REG_R8W, "r8w" },
2, // { X86_REG_R9W, "r9w" },
2, // { X86_REG_R10W, "r10w" },
2, // { X86_REG_R11W, "r11w" },
2, // { X86_REG_R12W, "r12w" },
2, // { X86_REG_R13W, "r13w" },
2, // { X86_REG_R14W, "r14w" },
2, // { X86_REG_R15W, "r15w" },
};
// register size in 64bit mode
uint8_t regsize_map_64 [] = {
0, // { X86_REG_INVALID, NULL },
1, // { X86_REG_AH, "ah" },
1, // { X86_REG_AL, "al" },
2, // { X86_REG_AX, "ax" },
1, // { X86_REG_BH, "bh" },
1, // { X86_REG_BL, "bl" },
2, // { X86_REG_BP, "bp" },
1, // { X86_REG_BPL, "bpl" },
2, // { X86_REG_BX, "bx" },
1, // { X86_REG_CH, "ch" },
1, // { X86_REG_CL, "cl" },
2, // { X86_REG_CS, "cs" },
2, // { X86_REG_CX, "cx" },
1, // { X86_REG_DH, "dh" },
2, // { X86_REG_DI, "di" },
1, // { X86_REG_DIL, "dil" },
1, // { X86_REG_DL, "dl" },
2, // { X86_REG_DS, "ds" },
2, // { X86_REG_DX, "dx" },
4, // { X86_REG_EAX, "eax" },
4, // { X86_REG_EBP, "ebp" },
4, // { X86_REG_EBX, "ebx" },
4, // { X86_REG_ECX, "ecx" },
4, // { X86_REG_EDI, "edi" },
4, // { X86_REG_EDX, "edx" },
8, // { X86_REG_EFLAGS, "flags" },
4, // { X86_REG_EIP, "eip" },
4, // { X86_REG_EIZ, "eiz" },
2, // { X86_REG_ES, "es" },
4, // { X86_REG_ESI, "esi" },
4, // { X86_REG_ESP, "esp" },
10, // { X86_REG_FPSW, "fpsw" },
2, // { X86_REG_FS, "fs" },
2, // { X86_REG_GS, "gs" },
2, // { X86_REG_IP, "ip" },
8, // { X86_REG_RAX, "rax" },
8, // { X86_REG_RBP, "rbp" },
8, // { X86_REG_RBX, "rbx" },
8, // { X86_REG_RCX, "rcx" },
8, // { X86_REG_RDI, "rdi" },
8, // { X86_REG_RDX, "rdx" },
8, // { X86_REG_RIP, "rip" },
8, // { X86_REG_RIZ, "riz" },
8, // { X86_REG_RSI, "rsi" },
8, // { X86_REG_RSP, "rsp" },
2, // { X86_REG_SI, "si" },
1, // { X86_REG_SIL, "sil" },
2, // { X86_REG_SP, "sp" },
1, // { X86_REG_SPL, "spl" },
2, // { X86_REG_SS, "ss" },
8, // { X86_REG_CR0, "cr0" },
8, // { X86_REG_CR1, "cr1" },
8, // { X86_REG_CR2, "cr2" },
8, // { X86_REG_CR3, "cr3" },
8, // { X86_REG_CR4, "cr4" },
8, // { X86_REG_CR5, "cr5" },
8, // { X86_REG_CR6, "cr6" },
8, // { X86_REG_CR7, "cr7" },
8, // { X86_REG_CR8, "cr8" },
8, // { X86_REG_CR9, "cr9" },
8, // { X86_REG_CR10, "cr10" },
8, // { X86_REG_CR11, "cr11" },
8, // { X86_REG_CR12, "cr12" },
8, // { X86_REG_CR13, "cr13" },
8, // { X86_REG_CR14, "cr14" },
8, // { X86_REG_CR15, "cr15" },
8, // { X86_REG_DR0, "dr0" },
8, // { X86_REG_DR1, "dr1" },
8, // { X86_REG_DR2, "dr2" },
8, // { X86_REG_DR3, "dr3" },
8, // { X86_REG_DR4, "dr4" },
8, // { X86_REG_DR5, "dr5" },
8, // { X86_REG_DR6, "dr6" },
8, // { X86_REG_DR7, "dr7" },
8, // { X86_REG_DR8, "dr8" },
8, // { X86_REG_DR9, "dr9" },
8, // { X86_REG_DR10, "dr10" },
8, // { X86_REG_DR11, "dr11" },
8, // { X86_REG_DR12, "dr12" },
8, // { X86_REG_DR13, "dr13" },
8, // { X86_REG_DR14, "dr14" },
8, // { X86_REG_DR15, "dr15" },
10, // { X86_REG_FP0, "fp0" },
10, // { X86_REG_FP1, "fp1" },
10, // { X86_REG_FP2, "fp2" },
10, // { X86_REG_FP3, "fp3" },
10, // { X86_REG_FP4, "fp4" },
10, // { X86_REG_FP5, "fp5" },
10, // { X86_REG_FP6, "fp6" },
10, // { X86_REG_FP7, "fp7" },
2, // { X86_REG_K0, "k0" },
2, // { X86_REG_K1, "k1" },
2, // { X86_REG_K2, "k2" },
2, // { X86_REG_K3, "k3" },
2, // { X86_REG_K4, "k4" },
2, // { X86_REG_K5, "k5" },
2, // { X86_REG_K6, "k6" },
2, // { X86_REG_K7, "k7" },
8, // { X86_REG_MM0, "mm0" },
8, // { X86_REG_MM1, "mm1" },
8, // { X86_REG_MM2, "mm2" },
8, // { X86_REG_MM3, "mm3" },
8, // { X86_REG_MM4, "mm4" },
8, // { X86_REG_MM5, "mm5" },
8, // { X86_REG_MM6, "mm6" },
8, // { X86_REG_MM7, "mm7" },
8, // { X86_REG_R8, "r8" },
8, // { X86_REG_R9, "r9" },
8, // { X86_REG_R10, "r10" },
8, // { X86_REG_R11, "r11" },
8, // { X86_REG_R12, "r12" },
8, // { X86_REG_R13, "r13" },
8, // { X86_REG_R14, "r14" },
8, // { X86_REG_R15, "r15" },
10, // { X86_REG_ST0, "st0" },
10, // { X86_REG_ST1, "st1" },
10, // { X86_REG_ST2, "st2" },
10, // { X86_REG_ST3, "st3" },
10, // { X86_REG_ST4, "st4" },
10, // { X86_REG_ST5, "st5" },
10, // { X86_REG_ST6, "st6" },
10, // { X86_REG_ST7, "st7" },
16, // { X86_REG_XMM0, "xmm0" },
16, // { X86_REG_XMM1, "xmm1" },
16, // { X86_REG_XMM2, "xmm2" },
16, // { X86_REG_XMM3, "xmm3" },
16, // { X86_REG_XMM4, "xmm4" },
16, // { X86_REG_XMM5, "xmm5" },
16, // { X86_REG_XMM6, "xmm6" },
16, // { X86_REG_XMM7, "xmm7" },
16, // { X86_REG_XMM8, "xmm8" },
16, // { X86_REG_XMM9, "xmm9" },
16, // { X86_REG_XMM10, "xmm10" },
16, // { X86_REG_XMM11, "xmm11" },
16, // { X86_REG_XMM12, "xmm12" },
16, // { X86_REG_XMM13, "xmm13" },
16, // { X86_REG_XMM14, "xmm14" },
16, // { X86_REG_XMM15, "xmm15" },
16, // { X86_REG_XMM16, "xmm16" },
16, // { X86_REG_XMM17, "xmm17" },
16, // { X86_REG_XMM18, "xmm18" },
16, // { X86_REG_XMM19, "xmm19" },
16, // { X86_REG_XMM20, "xmm20" },
16, // { X86_REG_XMM21, "xmm21" },
16, // { X86_REG_XMM22, "xmm22" },
16, // { X86_REG_XMM23, "xmm23" },
16, // { X86_REG_XMM24, "xmm24" },
16, // { X86_REG_XMM25, "xmm25" },
16, // { X86_REG_XMM26, "xmm26" },
16, // { X86_REG_XMM27, "xmm27" },
16, // { X86_REG_XMM28, "xmm28" },
16, // { X86_REG_XMM29, "xmm29" },
16, // { X86_REG_XMM30, "xmm30" },
16, // { X86_REG_XMM31, "xmm31" },
32, // { X86_REG_YMM0, "ymm0" },
32, // { X86_REG_YMM1, "ymm1" },
32, // { X86_REG_YMM2, "ymm2" },
32, // { X86_REG_YMM3, "ymm3" },
32, // { X86_REG_YMM4, "ymm4" },
32, // { X86_REG_YMM5, "ymm5" },
32, // { X86_REG_YMM6, "ymm6" },
32, // { X86_REG_YMM7, "ymm7" },
32, // { X86_REG_YMM8, "ymm8" },
32, // { X86_REG_YMM9, "ymm9" },
32, // { X86_REG_YMM10, "ymm10" },
32, // { X86_REG_YMM11, "ymm11" },
32, // { X86_REG_YMM12, "ymm12" },
32, // { X86_REG_YMM13, "ymm13" },
32, // { X86_REG_YMM14, "ymm14" },
32, // { X86_REG_YMM15, "ymm15" },
32, // { X86_REG_YMM16, "ymm16" },
32, // { X86_REG_YMM17, "ymm17" },
32, // { X86_REG_YMM18, "ymm18" },
32, // { X86_REG_YMM19, "ymm19" },
32, // { X86_REG_YMM20, "ymm20" },
32, // { X86_REG_YMM21, "ymm21" },
32, // { X86_REG_YMM22, "ymm22" },
32, // { X86_REG_YMM23, "ymm23" },
32, // { X86_REG_YMM24, "ymm24" },
32, // { X86_REG_YMM25, "ymm25" },
32, // { X86_REG_YMM26, "ymm26" },
32, // { X86_REG_YMM27, "ymm27" },
32, // { X86_REG_YMM28, "ymm28" },
32, // { X86_REG_YMM29, "ymm29" },
32, // { X86_REG_YMM30, "ymm30" },
32, // { X86_REG_YMM31, "ymm31" },
64, // { X86_REG_ZMM0, "zmm0" },
64, // { X86_REG_ZMM1, "zmm1" },
64, // { X86_REG_ZMM2, "zmm2" },
64, // { X86_REG_ZMM3, "zmm3" },
64, // { X86_REG_ZMM4, "zmm4" },
64, // { X86_REG_ZMM5, "zmm5" },
64, // { X86_REG_ZMM6, "zmm6" },
64, // { X86_REG_ZMM7, "zmm7" },
64, // { X86_REG_ZMM8, "zmm8" },
64, // { X86_REG_ZMM9, "zmm9" },
64, // { X86_REG_ZMM10, "zmm10" },
64, // { X86_REG_ZMM11, "zmm11" },
64, // { X86_REG_ZMM12, "zmm12" },
64, // { X86_REG_ZMM13, "zmm13" },
64, // { X86_REG_ZMM14, "zmm14" },
64, // { X86_REG_ZMM15, "zmm15" },
64, // { X86_REG_ZMM16, "zmm16" },
64, // { X86_REG_ZMM17, "zmm17" },
64, // { X86_REG_ZMM18, "zmm18" },
64, // { X86_REG_ZMM19, "zmm19" },
64, // { X86_REG_ZMM20, "zmm20" },
64, // { X86_REG_ZMM21, "zmm21" },
64, // { X86_REG_ZMM22, "zmm22" },
64, // { X86_REG_ZMM23, "zmm23" },
64, // { X86_REG_ZMM24, "zmm24" },
64, // { X86_REG_ZMM25, "zmm25" },
64, // { X86_REG_ZMM26, "zmm26" },
64, // { X86_REG_ZMM27, "zmm27" },
64, // { X86_REG_ZMM28, "zmm28" },
64, // { X86_REG_ZMM29, "zmm29" },
64, // { X86_REG_ZMM30, "zmm30" },
64, // { X86_REG_ZMM31, "zmm31" },
1, // { X86_REG_R8B, "r8b" },
1, // { X86_REG_R9B, "r9b" },
1, // { X86_REG_R10B, "r10b" },
1, // { X86_REG_R11B, "r11b" },
1, // { X86_REG_R12B, "r12b" },
1, // { X86_REG_R13B, "r13b" },
1, // { X86_REG_R14B, "r14b" },
1, // { X86_REG_R15B, "r15b" },
4, // { X86_REG_R8D, "r8d" },
4, // { X86_REG_R9D, "r9d" },
4, // { X86_REG_R10D, "r10d" },
4, // { X86_REG_R11D, "r11d" },
4, // { X86_REG_R12D, "r12d" },
4, // { X86_REG_R13D, "r13d" },
4, // { X86_REG_R14D, "r14d" },
4, // { X86_REG_R15D, "r15d" },
2, // { X86_REG_R8W, "r8w" },
2, // { X86_REG_R9W, "r9w" },
2, // { X86_REG_R10W, "r10w" },
2, // { X86_REG_R11W, "r11w" },
2, // { X86_REG_R12W, "r12w" },
2, // { X86_REG_R13W, "r13w" },
2, // { X86_REG_R14W, "r14w" },
2, // { X86_REG_R15W, "r15w" },
};
const char *X86_reg_name(csh handle, unsigned int reg)
{
#ifndef CAPSTONE_DIET
cs_struct *ud = (cs_struct *)handle;
if (reg >= X86_REG_ENDING)
return NULL;
if (reg == X86_REG_EFLAGS) {
if (ud->mode & CS_MODE_32)
return "eflags";
if (ud->mode & CS_MODE_64)
return "rflags";
}
return reg_name_maps[reg].name;
#else
return NULL;
#endif
}
#ifndef CAPSTONE_DIET
static name_map insn_name_maps[] = {
{ X86_INS_INVALID, NULL },
{ X86_INS_AAA, "aaa" },
{ X86_INS_AAD, "aad" },
{ X86_INS_AAM, "aam" },
{ X86_INS_AAS, "aas" },
{ X86_INS_FABS, "fabs" },
{ X86_INS_ADC, "adc" },
{ X86_INS_ADCX, "adcx" },
{ X86_INS_ADD, "add" },
{ X86_INS_ADDPD, "addpd" },
{ X86_INS_ADDPS, "addps" },
{ X86_INS_ADDSD, "addsd" },
{ X86_INS_ADDSS, "addss" },
{ X86_INS_ADDSUBPD, "addsubpd" },
{ X86_INS_ADDSUBPS, "addsubps" },
{ X86_INS_FADD, "fadd" },
{ X86_INS_FIADD, "fiadd" },
{ X86_INS_FADDP, "faddp" },
{ X86_INS_ADOX, "adox" },
{ X86_INS_AESDECLAST, "aesdeclast" },
{ X86_INS_AESDEC, "aesdec" },
{ X86_INS_AESENCLAST, "aesenclast" },
{ X86_INS_AESENC, "aesenc" },
{ X86_INS_AESIMC, "aesimc" },
{ X86_INS_AESKEYGENASSIST, "aeskeygenassist" },
{ X86_INS_AND, "and" },
{ X86_INS_ANDN, "andn" },
{ X86_INS_ANDNPD, "andnpd" },
{ X86_INS_ANDNPS, "andnps" },
{ X86_INS_ANDPD, "andpd" },
{ X86_INS_ANDPS, "andps" },
{ X86_INS_ARPL, "arpl" },
{ X86_INS_BEXTR, "bextr" },
{ X86_INS_BLCFILL, "blcfill" },
{ X86_INS_BLCI, "blci" },
{ X86_INS_BLCIC, "blcic" },
{ X86_INS_BLCMSK, "blcmsk" },
{ X86_INS_BLCS, "blcs" },
{ X86_INS_BLENDPD, "blendpd" },
{ X86_INS_BLENDPS, "blendps" },
{ X86_INS_BLENDVPD, "blendvpd" },
{ X86_INS_BLENDVPS, "blendvps" },
{ X86_INS_BLSFILL, "blsfill" },
{ X86_INS_BLSI, "blsi" },
{ X86_INS_BLSIC, "blsic" },
{ X86_INS_BLSMSK, "blsmsk" },
{ X86_INS_BLSR, "blsr" },
{ X86_INS_BOUND, "bound" },
{ X86_INS_BSF, "bsf" },
{ X86_INS_BSR, "bsr" },
{ X86_INS_BSWAP, "bswap" },
{ X86_INS_BT, "bt" },
{ X86_INS_BTC, "btc" },
{ X86_INS_BTR, "btr" },
{ X86_INS_BTS, "bts" },
{ X86_INS_BZHI, "bzhi" },
{ X86_INS_CALL, "call" },
{ X86_INS_CBW, "cbw" },
{ X86_INS_CDQ, "cdq" },
{ X86_INS_CDQE, "cdqe" },
{ X86_INS_FCHS, "fchs" },
{ X86_INS_CLAC, "clac" },
{ X86_INS_CLC, "clc" },
{ X86_INS_CLD, "cld" },
{ X86_INS_CLFLUSH, "clflush" },
{ X86_INS_CLFLUSHOPT, "clflushopt" },
{ X86_INS_CLGI, "clgi" },
{ X86_INS_CLI, "cli" },
{ X86_INS_CLTS, "clts" },
{ X86_INS_CLWB, "clwb" },
{ X86_INS_CMC, "cmc" },
{ X86_INS_CMOVA, "cmova" },
{ X86_INS_CMOVAE, "cmovae" },
{ X86_INS_CMOVB, "cmovb" },
{ X86_INS_CMOVBE, "cmovbe" },
{ X86_INS_FCMOVBE, "fcmovbe" },
{ X86_INS_FCMOVB, "fcmovb" },
{ X86_INS_CMOVE, "cmove" },
{ X86_INS_FCMOVE, "fcmove" },
{ X86_INS_CMOVG, "cmovg" },
{ X86_INS_CMOVGE, "cmovge" },
{ X86_INS_CMOVL, "cmovl" },
{ X86_INS_CMOVLE, "cmovle" },
{ X86_INS_FCMOVNBE, "fcmovnbe" },
{ X86_INS_FCMOVNB, "fcmovnb" },
{ X86_INS_CMOVNE, "cmovne" },
{ X86_INS_FCMOVNE, "fcmovne" },
{ X86_INS_CMOVNO, "cmovno" },
{ X86_INS_CMOVNP, "cmovnp" },
{ X86_INS_FCMOVNU, "fcmovnu" },
{ X86_INS_CMOVNS, "cmovns" },
{ X86_INS_CMOVO, "cmovo" },
{ X86_INS_CMOVP, "cmovp" },
{ X86_INS_FCMOVU, "fcmovu" },
{ X86_INS_CMOVS, "cmovs" },
{ X86_INS_CMP, "cmp" },
{ X86_INS_CMPSB, "cmpsb" },
{ X86_INS_CMPSQ, "cmpsq" },
{ X86_INS_CMPSW, "cmpsw" },
{ X86_INS_CMPXCHG16B, "cmpxchg16b" },
{ X86_INS_CMPXCHG, "cmpxchg" },
{ X86_INS_CMPXCHG8B, "cmpxchg8b" },
{ X86_INS_COMISD, "comisd" },
{ X86_INS_COMISS, "comiss" },
{ X86_INS_FCOMP, "fcomp" },
{ X86_INS_FCOMPI, "fcompi" },
{ X86_INS_FCOMI, "fcomi" },
{ X86_INS_FCOM, "fcom" },
{ X86_INS_FCOS, "fcos" },
{ X86_INS_CPUID, "cpuid" },
{ X86_INS_CQO, "cqo" },
{ X86_INS_CRC32, "crc32" },
{ X86_INS_CVTDQ2PD, "cvtdq2pd" },
{ X86_INS_CVTDQ2PS, "cvtdq2ps" },
{ X86_INS_CVTPD2DQ, "cvtpd2dq" },
{ X86_INS_CVTPD2PS, "cvtpd2ps" },
{ X86_INS_CVTPS2DQ, "cvtps2dq" },
{ X86_INS_CVTPS2PD, "cvtps2pd" },
{ X86_INS_CVTSD2SI, "cvtsd2si" },
{ X86_INS_CVTSD2SS, "cvtsd2ss" },
{ X86_INS_CVTSI2SD, "cvtsi2sd" },
{ X86_INS_CVTSI2SS, "cvtsi2ss" },
{ X86_INS_CVTSS2SD, "cvtss2sd" },
{ X86_INS_CVTSS2SI, "cvtss2si" },
{ X86_INS_CVTTPD2DQ, "cvttpd2dq" },
{ X86_INS_CVTTPS2DQ, "cvttps2dq" },
{ X86_INS_CVTTSD2SI, "cvttsd2si" },
{ X86_INS_CVTTSS2SI, "cvttss2si" },
{ X86_INS_CWD, "cwd" },
{ X86_INS_CWDE, "cwde" },
{ X86_INS_DAA, "daa" },
{ X86_INS_DAS, "das" },
{ X86_INS_DATA16, "data16" },
{ X86_INS_DEC, "dec" },
{ X86_INS_DIV, "div" },
{ X86_INS_DIVPD, "divpd" },
{ X86_INS_DIVPS, "divps" },
{ X86_INS_FDIVR, "fdivr" },
{ X86_INS_FIDIVR, "fidivr" },
{ X86_INS_FDIVRP, "fdivrp" },
{ X86_INS_DIVSD, "divsd" },
{ X86_INS_DIVSS, "divss" },
{ X86_INS_FDIV, "fdiv" },
{ X86_INS_FIDIV, "fidiv" },
{ X86_INS_FDIVP, "fdivp" },
{ X86_INS_DPPD, "dppd" },
{ X86_INS_DPPS, "dpps" },
{ X86_INS_RET, "ret" },
{ X86_INS_ENCLS, "encls" },
{ X86_INS_ENCLU, "enclu" },
{ X86_INS_ENTER, "enter" },
{ X86_INS_EXTRACTPS, "extractps" },
{ X86_INS_EXTRQ, "extrq" },
{ X86_INS_F2XM1, "f2xm1" },
{ X86_INS_LCALL, "lcall" },
{ X86_INS_LJMP, "ljmp" },
{ X86_INS_FBLD, "fbld" },
{ X86_INS_FBSTP, "fbstp" },
{ X86_INS_FCOMPP, "fcompp" },
{ X86_INS_FDECSTP, "fdecstp" },
{ X86_INS_FEMMS, "femms" },
{ X86_INS_FFREE, "ffree" },
{ X86_INS_FICOM, "ficom" },
{ X86_INS_FICOMP, "ficomp" },
{ X86_INS_FINCSTP, "fincstp" },
{ X86_INS_FLDCW, "fldcw" },
{ X86_INS_FLDENV, "fldenv" },
{ X86_INS_FLDL2E, "fldl2e" },
{ X86_INS_FLDL2T, "fldl2t" },
{ X86_INS_FLDLG2, "fldlg2" },
{ X86_INS_FLDLN2, "fldln2" },
{ X86_INS_FLDPI, "fldpi" },
{ X86_INS_FNCLEX, "fnclex" },
{ X86_INS_FNINIT, "fninit" },
{ X86_INS_FNOP, "fnop" },
{ X86_INS_FNSTCW, "fnstcw" },
{ X86_INS_FNSTSW, "fnstsw" },
{ X86_INS_FPATAN, "fpatan" },
{ X86_INS_FPREM, "fprem" },
{ X86_INS_FPREM1, "fprem1" },
{ X86_INS_FPTAN, "fptan" },
{ X86_INS_FFREEP, "ffreep" },
{ X86_INS_FRNDINT, "frndint" },
{ X86_INS_FRSTOR, "frstor" },
{ X86_INS_FNSAVE, "fnsave" },
{ X86_INS_FSCALE, "fscale" },
{ X86_INS_FSETPM, "fsetpm" },
{ X86_INS_FSINCOS, "fsincos" },
{ X86_INS_FNSTENV, "fnstenv" },
{ X86_INS_FXAM, "fxam" },
{ X86_INS_FXRSTOR, "fxrstor" },
{ X86_INS_FXRSTOR64, "fxrstor64" },
{ X86_INS_FXSAVE, "fxsave" },
{ X86_INS_FXSAVE64, "fxsave64" },
{ X86_INS_FXTRACT, "fxtract" },
{ X86_INS_FYL2X, "fyl2x" },
{ X86_INS_FYL2XP1, "fyl2xp1" },
{ X86_INS_MOVAPD, "movapd" },
{ X86_INS_MOVAPS, "movaps" },
{ X86_INS_ORPD, "orpd" },
{ X86_INS_ORPS, "orps" },
{ X86_INS_VMOVAPD, "vmovapd" },
{ X86_INS_VMOVAPS, "vmovaps" },
{ X86_INS_XORPD, "xorpd" },
{ X86_INS_XORPS, "xorps" },
{ X86_INS_GETSEC, "getsec" },
{ X86_INS_HADDPD, "haddpd" },
{ X86_INS_HADDPS, "haddps" },
{ X86_INS_HLT, "hlt" },
{ X86_INS_HSUBPD, "hsubpd" },
{ X86_INS_HSUBPS, "hsubps" },
{ X86_INS_IDIV, "idiv" },
{ X86_INS_FILD, "fild" },
{ X86_INS_IMUL, "imul" },
{ X86_INS_IN, "in" },
{ X86_INS_INC, "inc" },
{ X86_INS_INSB, "insb" },
{ X86_INS_INSERTPS, "insertps" },
{ X86_INS_INSERTQ, "insertq" },
{ X86_INS_INSD, "insd" },
{ X86_INS_INSW, "insw" },
{ X86_INS_INT, "int" },
{ X86_INS_INT1, "int1" },
{ X86_INS_INT3, "int3" },
{ X86_INS_INTO, "into" },
{ X86_INS_INVD, "invd" },
{ X86_INS_INVEPT, "invept" },
{ X86_INS_INVLPG, "invlpg" },
{ X86_INS_INVLPGA, "invlpga" },
{ X86_INS_INVPCID, "invpcid" },
{ X86_INS_INVVPID, "invvpid" },
{ X86_INS_IRET, "iret" },
{ X86_INS_IRETD, "iretd" },
{ X86_INS_IRETQ, "iretq" },
{ X86_INS_FISTTP, "fisttp" },
{ X86_INS_FIST, "fist" },
{ X86_INS_FISTP, "fistp" },
{ X86_INS_UCOMISD, "ucomisd" },
{ X86_INS_UCOMISS, "ucomiss" },
{ X86_INS_VCOMISD, "vcomisd" },
{ X86_INS_VCOMISS, "vcomiss" },
{ X86_INS_VCVTSD2SS, "vcvtsd2ss" },
{ X86_INS_VCVTSI2SD, "vcvtsi2sd" },
{ X86_INS_VCVTSI2SS, "vcvtsi2ss" },
{ X86_INS_VCVTSS2SD, "vcvtss2sd" },
{ X86_INS_VCVTTSD2SI, "vcvttsd2si" },
{ X86_INS_VCVTTSD2USI, "vcvttsd2usi" },
{ X86_INS_VCVTTSS2SI, "vcvttss2si" },
{ X86_INS_VCVTTSS2USI, "vcvttss2usi" },
{ X86_INS_VCVTUSI2SD, "vcvtusi2sd" },
{ X86_INS_VCVTUSI2SS, "vcvtusi2ss" },
{ X86_INS_VUCOMISD, "vucomisd" },
{ X86_INS_VUCOMISS, "vucomiss" },
{ X86_INS_JAE, "jae" },
{ X86_INS_JA, "ja" },
{ X86_INS_JBE, "jbe" },
{ X86_INS_JB, "jb" },
{ X86_INS_JCXZ, "jcxz" },
{ X86_INS_JECXZ, "jecxz" },
{ X86_INS_JE, "je" },
{ X86_INS_JGE, "jge" },
{ X86_INS_JG, "jg" },
{ X86_INS_JLE, "jle" },
{ X86_INS_JL, "jl" },
{ X86_INS_JMP, "jmp" },
{ X86_INS_JNE, "jne" },
{ X86_INS_JNO, "jno" },
{ X86_INS_JNP, "jnp" },
{ X86_INS_JNS, "jns" },
{ X86_INS_JO, "jo" },
{ X86_INS_JP, "jp" },
{ X86_INS_JRCXZ, "jrcxz" },
{ X86_INS_JS, "js" },
{ X86_INS_KANDB, "kandb" },
{ X86_INS_KANDD, "kandd" },
{ X86_INS_KANDNB, "kandnb" },
{ X86_INS_KANDND, "kandnd" },
{ X86_INS_KANDNQ, "kandnq" },
{ X86_INS_KANDNW, "kandnw" },
{ X86_INS_KANDQ, "kandq" },
{ X86_INS_KANDW, "kandw" },
{ X86_INS_KMOVB, "kmovb" },
{ X86_INS_KMOVD, "kmovd" },
{ X86_INS_KMOVQ, "kmovq" },
{ X86_INS_KMOVW, "kmovw" },
{ X86_INS_KNOTB, "knotb" },
{ X86_INS_KNOTD, "knotd" },
{ X86_INS_KNOTQ, "knotq" },
{ X86_INS_KNOTW, "knotw" },
{ X86_INS_KORB, "korb" },
{ X86_INS_KORD, "kord" },
{ X86_INS_KORQ, "korq" },
{ X86_INS_KORTESTB, "kortestb" },
{ X86_INS_KORTESTD, "kortestd" },
{ X86_INS_KORTESTQ, "kortestq" },
{ X86_INS_KORTESTW, "kortestw" },
{ X86_INS_KORW, "korw" },
{ X86_INS_KSHIFTLB, "kshiftlb" },
{ X86_INS_KSHIFTLD, "kshiftld" },
{ X86_INS_KSHIFTLQ, "kshiftlq" },
{ X86_INS_KSHIFTLW, "kshiftlw" },
{ X86_INS_KSHIFTRB, "kshiftrb" },
{ X86_INS_KSHIFTRD, "kshiftrd" },
{ X86_INS_KSHIFTRQ, "kshiftrq" },
{ X86_INS_KSHIFTRW, "kshiftrw" },
{ X86_INS_KUNPCKBW, "kunpckbw" },
{ X86_INS_KXNORB, "kxnorb" },
{ X86_INS_KXNORD, "kxnord" },
{ X86_INS_KXNORQ, "kxnorq" },
{ X86_INS_KXNORW, "kxnorw" },
{ X86_INS_KXORB, "kxorb" },
{ X86_INS_KXORD, "kxord" },
{ X86_INS_KXORQ, "kxorq" },
{ X86_INS_KXORW, "kxorw" },
{ X86_INS_LAHF, "lahf" },
{ X86_INS_LAR, "lar" },
{ X86_INS_LDDQU, "lddqu" },
{ X86_INS_LDMXCSR, "ldmxcsr" },
{ X86_INS_LDS, "lds" },
{ X86_INS_FLDZ, "fldz" },
{ X86_INS_FLD1, "fld1" },
{ X86_INS_FLD, "fld" },
{ X86_INS_LEA, "lea" },
{ X86_INS_LEAVE, "leave" },
{ X86_INS_LES, "les" },
{ X86_INS_LFENCE, "lfence" },
{ X86_INS_LFS, "lfs" },
{ X86_INS_LGDT, "lgdt" },
{ X86_INS_LGS, "lgs" },
{ X86_INS_LIDT, "lidt" },
{ X86_INS_LLDT, "lldt" },
{ X86_INS_LMSW, "lmsw" },
{ X86_INS_OR, "or" },
{ X86_INS_SUB, "sub" },
{ X86_INS_XOR, "xor" },
{ X86_INS_LODSB, "lodsb" },
{ X86_INS_LODSD, "lodsd" },
{ X86_INS_LODSQ, "lodsq" },
{ X86_INS_LODSW, "lodsw" },
{ X86_INS_LOOP, "loop" },
{ X86_INS_LOOPE, "loope" },
{ X86_INS_LOOPNE, "loopne" },
{ X86_INS_RETF, "retf" },
{ X86_INS_RETFQ, "retfq" },
{ X86_INS_LSL, "lsl" },
{ X86_INS_LSS, "lss" },
{ X86_INS_LTR, "ltr" },
{ X86_INS_XADD, "xadd" },
{ X86_INS_LZCNT, "lzcnt" },
{ X86_INS_MASKMOVDQU, "maskmovdqu" },
{ X86_INS_MAXPD, "maxpd" },
{ X86_INS_MAXPS, "maxps" },
{ X86_INS_MAXSD, "maxsd" },
{ X86_INS_MAXSS, "maxss" },
{ X86_INS_MFENCE, "mfence" },
{ X86_INS_MINPD, "minpd" },
{ X86_INS_MINPS, "minps" },
{ X86_INS_MINSD, "minsd" },
{ X86_INS_MINSS, "minss" },
{ X86_INS_CVTPD2PI, "cvtpd2pi" },
{ X86_INS_CVTPI2PD, "cvtpi2pd" },
{ X86_INS_CVTPI2PS, "cvtpi2ps" },
{ X86_INS_CVTPS2PI, "cvtps2pi" },
{ X86_INS_CVTTPD2PI, "cvttpd2pi" },
{ X86_INS_CVTTPS2PI, "cvttps2pi" },
{ X86_INS_EMMS, "emms" },
{ X86_INS_MASKMOVQ, "maskmovq" },
{ X86_INS_MOVD, "movd" },
{ X86_INS_MOVDQ2Q, "movdq2q" },
{ X86_INS_MOVNTQ, "movntq" },
{ X86_INS_MOVQ2DQ, "movq2dq" },
{ X86_INS_MOVQ, "movq" },
{ X86_INS_PABSB, "pabsb" },
{ X86_INS_PABSD, "pabsd" },
{ X86_INS_PABSW, "pabsw" },
{ X86_INS_PACKSSDW, "packssdw" },
{ X86_INS_PACKSSWB, "packsswb" },
{ X86_INS_PACKUSWB, "packuswb" },
{ X86_INS_PADDB, "paddb" },
{ X86_INS_PADDD, "paddd" },
{ X86_INS_PADDQ, "paddq" },
{ X86_INS_PADDSB, "paddsb" },
{ X86_INS_PADDSW, "paddsw" },
{ X86_INS_PADDUSB, "paddusb" },
{ X86_INS_PADDUSW, "paddusw" },
{ X86_INS_PADDW, "paddw" },
{ X86_INS_PALIGNR, "palignr" },
{ X86_INS_PANDN, "pandn" },
{ X86_INS_PAND, "pand" },
{ X86_INS_PAVGB, "pavgb" },
{ X86_INS_PAVGW, "pavgw" },
{ X86_INS_PCMPEQB, "pcmpeqb" },
{ X86_INS_PCMPEQD, "pcmpeqd" },
{ X86_INS_PCMPEQW, "pcmpeqw" },
{ X86_INS_PCMPGTB, "pcmpgtb" },
{ X86_INS_PCMPGTD, "pcmpgtd" },
{ X86_INS_PCMPGTW, "pcmpgtw" },
{ X86_INS_PEXTRW, "pextrw" },
{ X86_INS_PHADDSW, "phaddsw" },
{ X86_INS_PHADDW, "phaddw" },
{ X86_INS_PHADDD, "phaddd" },
{ X86_INS_PHSUBD, "phsubd" },
{ X86_INS_PHSUBSW, "phsubsw" },
{ X86_INS_PHSUBW, "phsubw" },
{ X86_INS_PINSRW, "pinsrw" },
{ X86_INS_PMADDUBSW, "pmaddubsw" },
{ X86_INS_PMADDWD, "pmaddwd" },
{ X86_INS_PMAXSW, "pmaxsw" },
{ X86_INS_PMAXUB, "pmaxub" },
{ X86_INS_PMINSW, "pminsw" },
{ X86_INS_PMINUB, "pminub" },
{ X86_INS_PMOVMSKB, "pmovmskb" },
{ X86_INS_PMULHRSW, "pmulhrsw" },
{ X86_INS_PMULHUW, "pmulhuw" },
{ X86_INS_PMULHW, "pmulhw" },
{ X86_INS_PMULLW, "pmullw" },
{ X86_INS_PMULUDQ, "pmuludq" },
{ X86_INS_POR, "por" },
{ X86_INS_PSADBW, "psadbw" },
{ X86_INS_PSHUFB, "pshufb" },
{ X86_INS_PSHUFW, "pshufw" },
{ X86_INS_PSIGNB, "psignb" },
{ X86_INS_PSIGND, "psignd" },
{ X86_INS_PSIGNW, "psignw" },
{ X86_INS_PSLLD, "pslld" },
{ X86_INS_PSLLQ, "psllq" },
{ X86_INS_PSLLW, "psllw" },
{ X86_INS_PSRAD, "psrad" },
{ X86_INS_PSRAW, "psraw" },
{ X86_INS_PSRLD, "psrld" },
{ X86_INS_PSRLQ, "psrlq" },
{ X86_INS_PSRLW, "psrlw" },
{ X86_INS_PSUBB, "psubb" },
{ X86_INS_PSUBD, "psubd" },
{ X86_INS_PSUBQ, "psubq" },
{ X86_INS_PSUBSB, "psubsb" },
{ X86_INS_PSUBSW, "psubsw" },
{ X86_INS_PSUBUSB, "psubusb" },
{ X86_INS_PSUBUSW, "psubusw" },
{ X86_INS_PSUBW, "psubw" },
{ X86_INS_PUNPCKHBW, "punpckhbw" },
{ X86_INS_PUNPCKHDQ, "punpckhdq" },
{ X86_INS_PUNPCKHWD, "punpckhwd" },
{ X86_INS_PUNPCKLBW, "punpcklbw" },
{ X86_INS_PUNPCKLDQ, "punpckldq" },
{ X86_INS_PUNPCKLWD, "punpcklwd" },
{ X86_INS_PXOR, "pxor" },
{ X86_INS_MONITOR, "monitor" },
{ X86_INS_MONTMUL, "montmul" },
{ X86_INS_MOV, "mov" },
{ X86_INS_MOVABS, "movabs" },
{ X86_INS_MOVBE, "movbe" },
{ X86_INS_MOVDDUP, "movddup" },
{ X86_INS_MOVDQA, "movdqa" },
{ X86_INS_MOVDQU, "movdqu" },
{ X86_INS_MOVHLPS, "movhlps" },
{ X86_INS_MOVHPD, "movhpd" },
{ X86_INS_MOVHPS, "movhps" },
{ X86_INS_MOVLHPS, "movlhps" },
{ X86_INS_MOVLPD, "movlpd" },
{ X86_INS_MOVLPS, "movlps" },
{ X86_INS_MOVMSKPD, "movmskpd" },
{ X86_INS_MOVMSKPS, "movmskps" },
{ X86_INS_MOVNTDQA, "movntdqa" },
{ X86_INS_MOVNTDQ, "movntdq" },
{ X86_INS_MOVNTI, "movnti" },
{ X86_INS_MOVNTPD, "movntpd" },
{ X86_INS_MOVNTPS, "movntps" },
{ X86_INS_MOVNTSD, "movntsd" },
{ X86_INS_MOVNTSS, "movntss" },
{ X86_INS_MOVSB, "movsb" },
{ X86_INS_MOVSD, "movsd" },
{ X86_INS_MOVSHDUP, "movshdup" },
{ X86_INS_MOVSLDUP, "movsldup" },
{ X86_INS_MOVSQ, "movsq" },
{ X86_INS_MOVSS, "movss" },
{ X86_INS_MOVSW, "movsw" },
{ X86_INS_MOVSX, "movsx" },
{ X86_INS_MOVSXD, "movsxd" },
{ X86_INS_MOVUPD, "movupd" },
{ X86_INS_MOVUPS, "movups" },
{ X86_INS_MOVZX, "movzx" },
{ X86_INS_MPSADBW, "mpsadbw" },
{ X86_INS_MUL, "mul" },
{ X86_INS_MULPD, "mulpd" },
{ X86_INS_MULPS, "mulps" },
{ X86_INS_MULSD, "mulsd" },
{ X86_INS_MULSS, "mulss" },
{ X86_INS_MULX, "mulx" },
{ X86_INS_FMUL, "fmul" },
{ X86_INS_FIMUL, "fimul" },
{ X86_INS_FMULP, "fmulp" },
{ X86_INS_MWAIT, "mwait" },
{ X86_INS_NEG, "neg" },
{ X86_INS_NOP, "nop" },
{ X86_INS_NOT, "not" },
{ X86_INS_OUT, "out" },
{ X86_INS_OUTSB, "outsb" },
{ X86_INS_OUTSD, "outsd" },
{ X86_INS_OUTSW, "outsw" },
{ X86_INS_PACKUSDW, "packusdw" },
{ X86_INS_PAUSE, "pause" },
{ X86_INS_PAVGUSB, "pavgusb" },
{ X86_INS_PBLENDVB, "pblendvb" },
{ X86_INS_PBLENDW, "pblendw" },
{ X86_INS_PCLMULQDQ, "pclmulqdq" },
{ X86_INS_PCMPEQQ, "pcmpeqq" },
{ X86_INS_PCMPESTRI, "pcmpestri" },
{ X86_INS_PCMPESTRM, "pcmpestrm" },
{ X86_INS_PCMPGTQ, "pcmpgtq" },
{ X86_INS_PCMPISTRI, "pcmpistri" },
{ X86_INS_PCMPISTRM, "pcmpistrm" },
{ X86_INS_PCOMMIT, "pcommit" },
{ X86_INS_PDEP, "pdep" },
{ X86_INS_PEXT, "pext" },
{ X86_INS_PEXTRB, "pextrb" },
{ X86_INS_PEXTRD, "pextrd" },
{ X86_INS_PEXTRQ, "pextrq" },
{ X86_INS_PF2ID, "pf2id" },
{ X86_INS_PF2IW, "pf2iw" },
{ X86_INS_PFACC, "pfacc" },
{ X86_INS_PFADD, "pfadd" },
{ X86_INS_PFCMPEQ, "pfcmpeq" },
{ X86_INS_PFCMPGE, "pfcmpge" },
{ X86_INS_PFCMPGT, "pfcmpgt" },
{ X86_INS_PFMAX, "pfmax" },
{ X86_INS_PFMIN, "pfmin" },
{ X86_INS_PFMUL, "pfmul" },
{ X86_INS_PFNACC, "pfnacc" },
{ X86_INS_PFPNACC, "pfpnacc" },
{ X86_INS_PFRCPIT1, "pfrcpit1" },
{ X86_INS_PFRCPIT2, "pfrcpit2" },
{ X86_INS_PFRCP, "pfrcp" },
{ X86_INS_PFRSQIT1, "pfrsqit1" },
{ X86_INS_PFRSQRT, "pfrsqrt" },
{ X86_INS_PFSUBR, "pfsubr" },
{ X86_INS_PFSUB, "pfsub" },
{ X86_INS_PHMINPOSUW, "phminposuw" },
{ X86_INS_PI2FD, "pi2fd" },
{ X86_INS_PI2FW, "pi2fw" },
{ X86_INS_PINSRB, "pinsrb" },
{ X86_INS_PINSRD, "pinsrd" },
{ X86_INS_PINSRQ, "pinsrq" },
{ X86_INS_PMAXSB, "pmaxsb" },
{ X86_INS_PMAXSD, "pmaxsd" },
{ X86_INS_PMAXUD, "pmaxud" },
{ X86_INS_PMAXUW, "pmaxuw" },
{ X86_INS_PMINSB, "pminsb" },
{ X86_INS_PMINSD, "pminsd" },
{ X86_INS_PMINUD, "pminud" },
{ X86_INS_PMINUW, "pminuw" },
{ X86_INS_PMOVSXBD, "pmovsxbd" },
{ X86_INS_PMOVSXBQ, "pmovsxbq" },
{ X86_INS_PMOVSXBW, "pmovsxbw" },
{ X86_INS_PMOVSXDQ, "pmovsxdq" },
{ X86_INS_PMOVSXWD, "pmovsxwd" },
{ X86_INS_PMOVSXWQ, "pmovsxwq" },
{ X86_INS_PMOVZXBD, "pmovzxbd" },
{ X86_INS_PMOVZXBQ, "pmovzxbq" },
{ X86_INS_PMOVZXBW, "pmovzxbw" },
{ X86_INS_PMOVZXDQ, "pmovzxdq" },
{ X86_INS_PMOVZXWD, "pmovzxwd" },
{ X86_INS_PMOVZXWQ, "pmovzxwq" },
{ X86_INS_PMULDQ, "pmuldq" },
{ X86_INS_PMULHRW, "pmulhrw" },
{ X86_INS_PMULLD, "pmulld" },
{ X86_INS_POP, "pop" },
{ X86_INS_POPAW, "popaw" },
{ X86_INS_POPAL, "popal" },
{ X86_INS_POPCNT, "popcnt" },
{ X86_INS_POPF, "popf" },
{ X86_INS_POPFD, "popfd" },
{ X86_INS_POPFQ, "popfq" },
{ X86_INS_PREFETCH, "prefetch" },
{ X86_INS_PREFETCHNTA, "prefetchnta" },
{ X86_INS_PREFETCHT0, "prefetcht0" },
{ X86_INS_PREFETCHT1, "prefetcht1" },
{ X86_INS_PREFETCHT2, "prefetcht2" },
{ X86_INS_PREFETCHW, "prefetchw" },
{ X86_INS_PSHUFD, "pshufd" },
{ X86_INS_PSHUFHW, "pshufhw" },
{ X86_INS_PSHUFLW, "pshuflw" },
{ X86_INS_PSLLDQ, "pslldq" },
{ X86_INS_PSRLDQ, "psrldq" },
{ X86_INS_PSWAPD, "pswapd" },
{ X86_INS_PTEST, "ptest" },
{ X86_INS_PUNPCKHQDQ, "punpckhqdq" },
{ X86_INS_PUNPCKLQDQ, "punpcklqdq" },
{ X86_INS_PUSH, "push" },
{ X86_INS_PUSHAW, "pushaw" },
{ X86_INS_PUSHAL, "pushal" },
{ X86_INS_PUSHF, "pushf" },
{ X86_INS_PUSHFD, "pushfd" },
{ X86_INS_PUSHFQ, "pushfq" },
{ X86_INS_RCL, "rcl" },
{ X86_INS_RCPPS, "rcpps" },
{ X86_INS_RCPSS, "rcpss" },
{ X86_INS_RCR, "rcr" },
{ X86_INS_RDFSBASE, "rdfsbase" },
{ X86_INS_RDGSBASE, "rdgsbase" },
{ X86_INS_RDMSR, "rdmsr" },
{ X86_INS_RDPMC, "rdpmc" },
{ X86_INS_RDRAND, "rdrand" },
{ X86_INS_RDSEED, "rdseed" },
{ X86_INS_RDTSC, "rdtsc" },
{ X86_INS_RDTSCP, "rdtscp" },
{ X86_INS_ROL, "rol" },
{ X86_INS_ROR, "ror" },
{ X86_INS_RORX, "rorx" },
{ X86_INS_ROUNDPD, "roundpd" },
{ X86_INS_ROUNDPS, "roundps" },
{ X86_INS_ROUNDSD, "roundsd" },
{ X86_INS_ROUNDSS, "roundss" },
{ X86_INS_RSM, "rsm" },
{ X86_INS_RSQRTPS, "rsqrtps" },
{ X86_INS_RSQRTSS, "rsqrtss" },
{ X86_INS_SAHF, "sahf" },
{ X86_INS_SAL, "sal" },
{ X86_INS_SALC, "salc" },
{ X86_INS_SAR, "sar" },
{ X86_INS_SARX, "sarx" },
{ X86_INS_SBB, "sbb" },
{ X86_INS_SCASB, "scasb" },
{ X86_INS_SCASD, "scasd" },
{ X86_INS_SCASQ, "scasq" },
{ X86_INS_SCASW, "scasw" },
{ X86_INS_SETAE, "setae" },
{ X86_INS_SETA, "seta" },
{ X86_INS_SETBE, "setbe" },
{ X86_INS_SETB, "setb" },
{ X86_INS_SETE, "sete" },
{ X86_INS_SETGE, "setge" },
{ X86_INS_SETG, "setg" },
{ X86_INS_SETLE, "setle" },
{ X86_INS_SETL, "setl" },
{ X86_INS_SETNE, "setne" },
{ X86_INS_SETNO, "setno" },
{ X86_INS_SETNP, "setnp" },
{ X86_INS_SETNS, "setns" },
{ X86_INS_SETO, "seto" },
{ X86_INS_SETP, "setp" },
{ X86_INS_SETS, "sets" },
{ X86_INS_SFENCE, "sfence" },
{ X86_INS_SGDT, "sgdt" },
{ X86_INS_SHA1MSG1, "sha1msg1" },
{ X86_INS_SHA1MSG2, "sha1msg2" },
{ X86_INS_SHA1NEXTE, "sha1nexte" },
{ X86_INS_SHA1RNDS4, "sha1rnds4" },
{ X86_INS_SHA256MSG1, "sha256msg1" },
{ X86_INS_SHA256MSG2, "sha256msg2" },
{ X86_INS_SHA256RNDS2, "sha256rnds2" },
{ X86_INS_SHL, "shl" },
{ X86_INS_SHLD, "shld" },
{ X86_INS_SHLX, "shlx" },
{ X86_INS_SHR, "shr" },
{ X86_INS_SHRD, "shrd" },
{ X86_INS_SHRX, "shrx" },
{ X86_INS_SHUFPD, "shufpd" },
{ X86_INS_SHUFPS, "shufps" },
{ X86_INS_SIDT, "sidt" },
{ X86_INS_FSIN, "fsin" },
{ X86_INS_SKINIT, "skinit" },
{ X86_INS_SLDT, "sldt" },
{ X86_INS_SMSW, "smsw" },
{ X86_INS_SQRTPD, "sqrtpd" },
{ X86_INS_SQRTPS, "sqrtps" },
{ X86_INS_SQRTSD, "sqrtsd" },
{ X86_INS_SQRTSS, "sqrtss" },
{ X86_INS_FSQRT, "fsqrt" },
{ X86_INS_STAC, "stac" },
{ X86_INS_STC, "stc" },
{ X86_INS_STD, "std" },
{ X86_INS_STGI, "stgi" },
{ X86_INS_STI, "sti" },
{ X86_INS_STMXCSR, "stmxcsr" },
{ X86_INS_STOSB, "stosb" },
{ X86_INS_STOSD, "stosd" },
{ X86_INS_STOSQ, "stosq" },
{ X86_INS_STOSW, "stosw" },
{ X86_INS_STR, "str" },
{ X86_INS_FST, "fst" },
{ X86_INS_FSTP, "fstp" },
{ X86_INS_FSTPNCE, "fstpnce" },
{ X86_INS_FXCH, "fxch" },
{ X86_INS_SUBPD, "subpd" },
{ X86_INS_SUBPS, "subps" },
{ X86_INS_FSUBR, "fsubr" },
{ X86_INS_FISUBR, "fisubr" },
{ X86_INS_FSUBRP, "fsubrp" },
{ X86_INS_SUBSD, "subsd" },
{ X86_INS_SUBSS, "subss" },
{ X86_INS_FSUB, "fsub" },
{ X86_INS_FISUB, "fisub" },
{ X86_INS_FSUBP, "fsubp" },
{ X86_INS_SWAPGS, "swapgs" },
{ X86_INS_SYSCALL, "syscall" },
{ X86_INS_SYSENTER, "sysenter" },
{ X86_INS_SYSEXIT, "sysexit" },
{ X86_INS_SYSRET, "sysret" },
{ X86_INS_T1MSKC, "t1mskc" },
{ X86_INS_TEST, "test" },
{ X86_INS_UD2, "ud2" },
{ X86_INS_FTST, "ftst" },
{ X86_INS_TZCNT, "tzcnt" },
{ X86_INS_TZMSK, "tzmsk" },
{ X86_INS_FUCOMPI, "fucompi" },
{ X86_INS_FUCOMI, "fucomi" },
{ X86_INS_FUCOMPP, "fucompp" },
{ X86_INS_FUCOMP, "fucomp" },
{ X86_INS_FUCOM, "fucom" },
{ X86_INS_UD2B, "ud2b" },
{ X86_INS_UNPCKHPD, "unpckhpd" },
{ X86_INS_UNPCKHPS, "unpckhps" },
{ X86_INS_UNPCKLPD, "unpcklpd" },
{ X86_INS_UNPCKLPS, "unpcklps" },
{ X86_INS_VADDPD, "vaddpd" },
{ X86_INS_VADDPS, "vaddps" },
{ X86_INS_VADDSD, "vaddsd" },
{ X86_INS_VADDSS, "vaddss" },
{ X86_INS_VADDSUBPD, "vaddsubpd" },
{ X86_INS_VADDSUBPS, "vaddsubps" },
{ X86_INS_VAESDECLAST, "vaesdeclast" },
{ X86_INS_VAESDEC, "vaesdec" },
{ X86_INS_VAESENCLAST, "vaesenclast" },
{ X86_INS_VAESENC, "vaesenc" },
{ X86_INS_VAESIMC, "vaesimc" },
{ X86_INS_VAESKEYGENASSIST, "vaeskeygenassist" },
{ X86_INS_VALIGND, "valignd" },
{ X86_INS_VALIGNQ, "valignq" },
{ X86_INS_VANDNPD, "vandnpd" },
{ X86_INS_VANDNPS, "vandnps" },
{ X86_INS_VANDPD, "vandpd" },
{ X86_INS_VANDPS, "vandps" },
{ X86_INS_VBLENDMPD, "vblendmpd" },
{ X86_INS_VBLENDMPS, "vblendmps" },
{ X86_INS_VBLENDPD, "vblendpd" },
{ X86_INS_VBLENDPS, "vblendps" },
{ X86_INS_VBLENDVPD, "vblendvpd" },
{ X86_INS_VBLENDVPS, "vblendvps" },
{ X86_INS_VBROADCASTF128, "vbroadcastf128" },
{ X86_INS_VBROADCASTI32X4, "vbroadcasti32x4" },
{ X86_INS_VBROADCASTI64X4, "vbroadcasti64x4" },
{ X86_INS_VBROADCASTSD, "vbroadcastsd" },
{ X86_INS_VBROADCASTSS, "vbroadcastss" },
{ X86_INS_VCOMPRESSPD, "vcompresspd" },
{ X86_INS_VCOMPRESSPS, "vcompressps" },
{ X86_INS_VCVTDQ2PD, "vcvtdq2pd" },
{ X86_INS_VCVTDQ2PS, "vcvtdq2ps" },
{ X86_INS_VCVTPD2DQX, "vcvtpd2dqx" },
{ X86_INS_VCVTPD2DQ, "vcvtpd2dq" },
{ X86_INS_VCVTPD2PSX, "vcvtpd2psx" },
{ X86_INS_VCVTPD2PS, "vcvtpd2ps" },
{ X86_INS_VCVTPD2UDQ, "vcvtpd2udq" },
{ X86_INS_VCVTPH2PS, "vcvtph2ps" },
{ X86_INS_VCVTPS2DQ, "vcvtps2dq" },
{ X86_INS_VCVTPS2PD, "vcvtps2pd" },
{ X86_INS_VCVTPS2PH, "vcvtps2ph" },
{ X86_INS_VCVTPS2UDQ, "vcvtps2udq" },
{ X86_INS_VCVTSD2SI, "vcvtsd2si" },
{ X86_INS_VCVTSD2USI, "vcvtsd2usi" },
{ X86_INS_VCVTSS2SI, "vcvtss2si" },
{ X86_INS_VCVTSS2USI, "vcvtss2usi" },
{ X86_INS_VCVTTPD2DQX, "vcvttpd2dqx" },
{ X86_INS_VCVTTPD2DQ, "vcvttpd2dq" },
{ X86_INS_VCVTTPD2UDQ, "vcvttpd2udq" },
{ X86_INS_VCVTTPS2DQ, "vcvttps2dq" },
{ X86_INS_VCVTTPS2UDQ, "vcvttps2udq" },
{ X86_INS_VCVTUDQ2PD, "vcvtudq2pd" },
{ X86_INS_VCVTUDQ2PS, "vcvtudq2ps" },
{ X86_INS_VDIVPD, "vdivpd" },
{ X86_INS_VDIVPS, "vdivps" },
{ X86_INS_VDIVSD, "vdivsd" },
{ X86_INS_VDIVSS, "vdivss" },
{ X86_INS_VDPPD, "vdppd" },
{ X86_INS_VDPPS, "vdpps" },
{ X86_INS_VERR, "verr" },
{ X86_INS_VERW, "verw" },
{ X86_INS_VEXP2PD, "vexp2pd" },
{ X86_INS_VEXP2PS, "vexp2ps" },
{ X86_INS_VEXPANDPD, "vexpandpd" },
{ X86_INS_VEXPANDPS, "vexpandps" },
{ X86_INS_VEXTRACTF128, "vextractf128" },
{ X86_INS_VEXTRACTF32X4, "vextractf32x4" },
{ X86_INS_VEXTRACTF64X4, "vextractf64x4" },
{ X86_INS_VEXTRACTI128, "vextracti128" },
{ X86_INS_VEXTRACTI32X4, "vextracti32x4" },
{ X86_INS_VEXTRACTI64X4, "vextracti64x4" },
{ X86_INS_VEXTRACTPS, "vextractps" },
{ X86_INS_VFMADD132PD, "vfmadd132pd" },
{ X86_INS_VFMADD132PS, "vfmadd132ps" },
{ X86_INS_VFMADDPD, "vfmaddpd" },
{ X86_INS_VFMADD213PD, "vfmadd213pd" },
{ X86_INS_VFMADD231PD, "vfmadd231pd" },
{ X86_INS_VFMADDPS, "vfmaddps" },
{ X86_INS_VFMADD213PS, "vfmadd213ps" },
{ X86_INS_VFMADD231PS, "vfmadd231ps" },
{ X86_INS_VFMADDSD, "vfmaddsd" },
{ X86_INS_VFMADD213SD, "vfmadd213sd" },
{ X86_INS_VFMADD132SD, "vfmadd132sd" },
{ X86_INS_VFMADD231SD, "vfmadd231sd" },
{ X86_INS_VFMADDSS, "vfmaddss" },
{ X86_INS_VFMADD213SS, "vfmadd213ss" },
{ X86_INS_VFMADD132SS, "vfmadd132ss" },
{ X86_INS_VFMADD231SS, "vfmadd231ss" },
{ X86_INS_VFMADDSUB132PD, "vfmaddsub132pd" },
{ X86_INS_VFMADDSUB132PS, "vfmaddsub132ps" },
{ X86_INS_VFMADDSUBPD, "vfmaddsubpd" },
{ X86_INS_VFMADDSUB213PD, "vfmaddsub213pd" },
{ X86_INS_VFMADDSUB231PD, "vfmaddsub231pd" },
{ X86_INS_VFMADDSUBPS, "vfmaddsubps" },
{ X86_INS_VFMADDSUB213PS, "vfmaddsub213ps" },
{ X86_INS_VFMADDSUB231PS, "vfmaddsub231ps" },
{ X86_INS_VFMSUB132PD, "vfmsub132pd" },
{ X86_INS_VFMSUB132PS, "vfmsub132ps" },
{ X86_INS_VFMSUBADD132PD, "vfmsubadd132pd" },
{ X86_INS_VFMSUBADD132PS, "vfmsubadd132ps" },
{ X86_INS_VFMSUBADDPD, "vfmsubaddpd" },
{ X86_INS_VFMSUBADD213PD, "vfmsubadd213pd" },
{ X86_INS_VFMSUBADD231PD, "vfmsubadd231pd" },
{ X86_INS_VFMSUBADDPS, "vfmsubaddps" },
{ X86_INS_VFMSUBADD213PS, "vfmsubadd213ps" },
{ X86_INS_VFMSUBADD231PS, "vfmsubadd231ps" },
{ X86_INS_VFMSUBPD, "vfmsubpd" },
{ X86_INS_VFMSUB213PD, "vfmsub213pd" },
{ X86_INS_VFMSUB231PD, "vfmsub231pd" },
{ X86_INS_VFMSUBPS, "vfmsubps" },
{ X86_INS_VFMSUB213PS, "vfmsub213ps" },
{ X86_INS_VFMSUB231PS, "vfmsub231ps" },
{ X86_INS_VFMSUBSD, "vfmsubsd" },
{ X86_INS_VFMSUB213SD, "vfmsub213sd" },
{ X86_INS_VFMSUB132SD, "vfmsub132sd" },
{ X86_INS_VFMSUB231SD, "vfmsub231sd" },
{ X86_INS_VFMSUBSS, "vfmsubss" },
{ X86_INS_VFMSUB213SS, "vfmsub213ss" },
{ X86_INS_VFMSUB132SS, "vfmsub132ss" },
{ X86_INS_VFMSUB231SS, "vfmsub231ss" },
{ X86_INS_VFNMADD132PD, "vfnmadd132pd" },
{ X86_INS_VFNMADD132PS, "vfnmadd132ps" },
{ X86_INS_VFNMADDPD, "vfnmaddpd" },
{ X86_INS_VFNMADD213PD, "vfnmadd213pd" },
{ X86_INS_VFNMADD231PD, "vfnmadd231pd" },
{ X86_INS_VFNMADDPS, "vfnmaddps" },
{ X86_INS_VFNMADD213PS, "vfnmadd213ps" },
{ X86_INS_VFNMADD231PS, "vfnmadd231ps" },
{ X86_INS_VFNMADDSD, "vfnmaddsd" },
{ X86_INS_VFNMADD213SD, "vfnmadd213sd" },
{ X86_INS_VFNMADD132SD, "vfnmadd132sd" },
{ X86_INS_VFNMADD231SD, "vfnmadd231sd" },
{ X86_INS_VFNMADDSS, "vfnmaddss" },
{ X86_INS_VFNMADD213SS, "vfnmadd213ss" },
{ X86_INS_VFNMADD132SS, "vfnmadd132ss" },
{ X86_INS_VFNMADD231SS, "vfnmadd231ss" },
{ X86_INS_VFNMSUB132PD, "vfnmsub132pd" },
{ X86_INS_VFNMSUB132PS, "vfnmsub132ps" },
{ X86_INS_VFNMSUBPD, "vfnmsubpd" },
{ X86_INS_VFNMSUB213PD, "vfnmsub213pd" },
{ X86_INS_VFNMSUB231PD, "vfnmsub231pd" },
{ X86_INS_VFNMSUBPS, "vfnmsubps" },
{ X86_INS_VFNMSUB213PS, "vfnmsub213ps" },
{ X86_INS_VFNMSUB231PS, "vfnmsub231ps" },
{ X86_INS_VFNMSUBSD, "vfnmsubsd" },
{ X86_INS_VFNMSUB213SD, "vfnmsub213sd" },
{ X86_INS_VFNMSUB132SD, "vfnmsub132sd" },
{ X86_INS_VFNMSUB231SD, "vfnmsub231sd" },
{ X86_INS_VFNMSUBSS, "vfnmsubss" },
{ X86_INS_VFNMSUB213SS, "vfnmsub213ss" },
{ X86_INS_VFNMSUB132SS, "vfnmsub132ss" },
{ X86_INS_VFNMSUB231SS, "vfnmsub231ss" },
{ X86_INS_VFRCZPD, "vfrczpd" },
{ X86_INS_VFRCZPS, "vfrczps" },
{ X86_INS_VFRCZSD, "vfrczsd" },
{ X86_INS_VFRCZSS, "vfrczss" },
{ X86_INS_VORPD, "vorpd" },
{ X86_INS_VORPS, "vorps" },
{ X86_INS_VXORPD, "vxorpd" },
{ X86_INS_VXORPS, "vxorps" },
{ X86_INS_VGATHERDPD, "vgatherdpd" },
{ X86_INS_VGATHERDPS, "vgatherdps" },
{ X86_INS_VGATHERPF0DPD, "vgatherpf0dpd" },
{ X86_INS_VGATHERPF0DPS, "vgatherpf0dps" },
{ X86_INS_VGATHERPF0QPD, "vgatherpf0qpd" },
{ X86_INS_VGATHERPF0QPS, "vgatherpf0qps" },
{ X86_INS_VGATHERPF1DPD, "vgatherpf1dpd" },
{ X86_INS_VGATHERPF1DPS, "vgatherpf1dps" },
{ X86_INS_VGATHERPF1QPD, "vgatherpf1qpd" },
{ X86_INS_VGATHERPF1QPS, "vgatherpf1qps" },
{ X86_INS_VGATHERQPD, "vgatherqpd" },
{ X86_INS_VGATHERQPS, "vgatherqps" },
{ X86_INS_VHADDPD, "vhaddpd" },
{ X86_INS_VHADDPS, "vhaddps" },
{ X86_INS_VHSUBPD, "vhsubpd" },
{ X86_INS_VHSUBPS, "vhsubps" },
{ X86_INS_VINSERTF128, "vinsertf128" },
{ X86_INS_VINSERTF32X4, "vinsertf32x4" },
{ X86_INS_VINSERTF32X8, "vinsertf32x8" },
{ X86_INS_VINSERTF64X2, "vinsertf64x2" },
{ X86_INS_VINSERTF64X4, "vinsertf64x4" },
{ X86_INS_VINSERTI128, "vinserti128" },
{ X86_INS_VINSERTI32X4, "vinserti32x4" },
{ X86_INS_VINSERTI32X8, "vinserti32x8" },
{ X86_INS_VINSERTI64X2, "vinserti64x2" },
{ X86_INS_VINSERTI64X4, "vinserti64x4" },
{ X86_INS_VINSERTPS, "vinsertps" },
{ X86_INS_VLDDQU, "vlddqu" },
{ X86_INS_VLDMXCSR, "vldmxcsr" },
{ X86_INS_VMASKMOVDQU, "vmaskmovdqu" },
{ X86_INS_VMASKMOVPD, "vmaskmovpd" },
{ X86_INS_VMASKMOVPS, "vmaskmovps" },
{ X86_INS_VMAXPD, "vmaxpd" },
{ X86_INS_VMAXPS, "vmaxps" },
{ X86_INS_VMAXSD, "vmaxsd" },
{ X86_INS_VMAXSS, "vmaxss" },
{ X86_INS_VMCALL, "vmcall" },
{ X86_INS_VMCLEAR, "vmclear" },
{ X86_INS_VMFUNC, "vmfunc" },
{ X86_INS_VMINPD, "vminpd" },
{ X86_INS_VMINPS, "vminps" },
{ X86_INS_VMINSD, "vminsd" },
{ X86_INS_VMINSS, "vminss" },
{ X86_INS_VMLAUNCH, "vmlaunch" },
{ X86_INS_VMLOAD, "vmload" },
{ X86_INS_VMMCALL, "vmmcall" },
{ X86_INS_VMOVQ, "vmovq" },
{ X86_INS_VMOVDDUP, "vmovddup" },
{ X86_INS_VMOVD, "vmovd" },
{ X86_INS_VMOVDQA32, "vmovdqa32" },
{ X86_INS_VMOVDQA64, "vmovdqa64" },
{ X86_INS_VMOVDQA, "vmovdqa" },
{ X86_INS_VMOVDQU16, "vmovdqu16" },
{ X86_INS_VMOVDQU32, "vmovdqu32" },
{ X86_INS_VMOVDQU64, "vmovdqu64" },
{ X86_INS_VMOVDQU8, "vmovdqu8" },
{ X86_INS_VMOVDQU, "vmovdqu" },
{ X86_INS_VMOVHLPS, "vmovhlps" },
{ X86_INS_VMOVHPD, "vmovhpd" },
{ X86_INS_VMOVHPS, "vmovhps" },
{ X86_INS_VMOVLHPS, "vmovlhps" },
{ X86_INS_VMOVLPD, "vmovlpd" },
{ X86_INS_VMOVLPS, "vmovlps" },
{ X86_INS_VMOVMSKPD, "vmovmskpd" },
{ X86_INS_VMOVMSKPS, "vmovmskps" },
{ X86_INS_VMOVNTDQA, "vmovntdqa" },
{ X86_INS_VMOVNTDQ, "vmovntdq" },
{ X86_INS_VMOVNTPD, "vmovntpd" },
{ X86_INS_VMOVNTPS, "vmovntps" },
{ X86_INS_VMOVSD, "vmovsd" },
{ X86_INS_VMOVSHDUP, "vmovshdup" },
{ X86_INS_VMOVSLDUP, "vmovsldup" },
{ X86_INS_VMOVSS, "vmovss" },
{ X86_INS_VMOVUPD, "vmovupd" },
{ X86_INS_VMOVUPS, "vmovups" },
{ X86_INS_VMPSADBW, "vmpsadbw" },
{ X86_INS_VMPTRLD, "vmptrld" },
{ X86_INS_VMPTRST, "vmptrst" },
{ X86_INS_VMREAD, "vmread" },
{ X86_INS_VMRESUME, "vmresume" },
{ X86_INS_VMRUN, "vmrun" },
{ X86_INS_VMSAVE, "vmsave" },
{ X86_INS_VMULPD, "vmulpd" },
{ X86_INS_VMULPS, "vmulps" },
{ X86_INS_VMULSD, "vmulsd" },
{ X86_INS_VMULSS, "vmulss" },
{ X86_INS_VMWRITE, "vmwrite" },
{ X86_INS_VMXOFF, "vmxoff" },
{ X86_INS_VMXON, "vmxon" },
{ X86_INS_VPABSB, "vpabsb" },
{ X86_INS_VPABSD, "vpabsd" },
{ X86_INS_VPABSQ, "vpabsq" },
{ X86_INS_VPABSW, "vpabsw" },
{ X86_INS_VPACKSSDW, "vpackssdw" },
{ X86_INS_VPACKSSWB, "vpacksswb" },
{ X86_INS_VPACKUSDW, "vpackusdw" },
{ X86_INS_VPACKUSWB, "vpackuswb" },
{ X86_INS_VPADDB, "vpaddb" },
{ X86_INS_VPADDD, "vpaddd" },
{ X86_INS_VPADDQ, "vpaddq" },
{ X86_INS_VPADDSB, "vpaddsb" },
{ X86_INS_VPADDSW, "vpaddsw" },
{ X86_INS_VPADDUSB, "vpaddusb" },
{ X86_INS_VPADDUSW, "vpaddusw" },
{ X86_INS_VPADDW, "vpaddw" },
{ X86_INS_VPALIGNR, "vpalignr" },
{ X86_INS_VPANDD, "vpandd" },
{ X86_INS_VPANDND, "vpandnd" },
{ X86_INS_VPANDNQ, "vpandnq" },
{ X86_INS_VPANDN, "vpandn" },
{ X86_INS_VPANDQ, "vpandq" },
{ X86_INS_VPAND, "vpand" },
{ X86_INS_VPAVGB, "vpavgb" },
{ X86_INS_VPAVGW, "vpavgw" },
{ X86_INS_VPBLENDD, "vpblendd" },
{ X86_INS_VPBLENDMB, "vpblendmb" },
{ X86_INS_VPBLENDMD, "vpblendmd" },
{ X86_INS_VPBLENDMQ, "vpblendmq" },
{ X86_INS_VPBLENDMW, "vpblendmw" },
{ X86_INS_VPBLENDVB, "vpblendvb" },
{ X86_INS_VPBLENDW, "vpblendw" },
{ X86_INS_VPBROADCASTB, "vpbroadcastb" },
{ X86_INS_VPBROADCASTD, "vpbroadcastd" },
{ X86_INS_VPBROADCASTMB2Q, "vpbroadcastmb2q" },
{ X86_INS_VPBROADCASTMW2D, "vpbroadcastmw2d" },
{ X86_INS_VPBROADCASTQ, "vpbroadcastq" },
{ X86_INS_VPBROADCASTW, "vpbroadcastw" },
{ X86_INS_VPCLMULQDQ, "vpclmulqdq" },
{ X86_INS_VPCMOV, "vpcmov" },
{ X86_INS_VPCMPB, "vpcmpb" },
{ X86_INS_VPCMPD, "vpcmpd" },
{ X86_INS_VPCMPEQB, "vpcmpeqb" },
{ X86_INS_VPCMPEQD, "vpcmpeqd" },
{ X86_INS_VPCMPEQQ, "vpcmpeqq" },
{ X86_INS_VPCMPEQW, "vpcmpeqw" },
{ X86_INS_VPCMPESTRI, "vpcmpestri" },
{ X86_INS_VPCMPESTRM, "vpcmpestrm" },
{ X86_INS_VPCMPGTB, "vpcmpgtb" },
{ X86_INS_VPCMPGTD, "vpcmpgtd" },
{ X86_INS_VPCMPGTQ, "vpcmpgtq" },
{ X86_INS_VPCMPGTW, "vpcmpgtw" },
{ X86_INS_VPCMPISTRI, "vpcmpistri" },
{ X86_INS_VPCMPISTRM, "vpcmpistrm" },
{ X86_INS_VPCMPQ, "vpcmpq" },
{ X86_INS_VPCMPUB, "vpcmpub" },
{ X86_INS_VPCMPUD, "vpcmpud" },
{ X86_INS_VPCMPUQ, "vpcmpuq" },
{ X86_INS_VPCMPUW, "vpcmpuw" },
{ X86_INS_VPCMPW, "vpcmpw" },
{ X86_INS_VPCOMB, "vpcomb" },
{ X86_INS_VPCOMD, "vpcomd" },
{ X86_INS_VPCOMPRESSD, "vpcompressd" },
{ X86_INS_VPCOMPRESSQ, "vpcompressq" },
{ X86_INS_VPCOMQ, "vpcomq" },
{ X86_INS_VPCOMUB, "vpcomub" },
{ X86_INS_VPCOMUD, "vpcomud" },
{ X86_INS_VPCOMUQ, "vpcomuq" },
{ X86_INS_VPCOMUW, "vpcomuw" },
{ X86_INS_VPCOMW, "vpcomw" },
{ X86_INS_VPCONFLICTD, "vpconflictd" },
{ X86_INS_VPCONFLICTQ, "vpconflictq" },
{ X86_INS_VPERM2F128, "vperm2f128" },
{ X86_INS_VPERM2I128, "vperm2i128" },
{ X86_INS_VPERMD, "vpermd" },
{ X86_INS_VPERMI2D, "vpermi2d" },
{ X86_INS_VPERMI2PD, "vpermi2pd" },
{ X86_INS_VPERMI2PS, "vpermi2ps" },
{ X86_INS_VPERMI2Q, "vpermi2q" },
{ X86_INS_VPERMIL2PD, "vpermil2pd" },
{ X86_INS_VPERMIL2PS, "vpermil2ps" },
{ X86_INS_VPERMILPD, "vpermilpd" },
{ X86_INS_VPERMILPS, "vpermilps" },
{ X86_INS_VPERMPD, "vpermpd" },
{ X86_INS_VPERMPS, "vpermps" },
{ X86_INS_VPERMQ, "vpermq" },
{ X86_INS_VPERMT2D, "vpermt2d" },
{ X86_INS_VPERMT2PD, "vpermt2pd" },
{ X86_INS_VPERMT2PS, "vpermt2ps" },
{ X86_INS_VPERMT2Q, "vpermt2q" },
{ X86_INS_VPEXPANDD, "vpexpandd" },
{ X86_INS_VPEXPANDQ, "vpexpandq" },
{ X86_INS_VPEXTRB, "vpextrb" },
{ X86_INS_VPEXTRD, "vpextrd" },
{ X86_INS_VPEXTRQ, "vpextrq" },
{ X86_INS_VPEXTRW, "vpextrw" },
{ X86_INS_VPGATHERDD, "vpgatherdd" },
{ X86_INS_VPGATHERDQ, "vpgatherdq" },
{ X86_INS_VPGATHERQD, "vpgatherqd" },
{ X86_INS_VPGATHERQQ, "vpgatherqq" },
{ X86_INS_VPHADDBD, "vphaddbd" },
{ X86_INS_VPHADDBQ, "vphaddbq" },
{ X86_INS_VPHADDBW, "vphaddbw" },
{ X86_INS_VPHADDDQ, "vphadddq" },
{ X86_INS_VPHADDD, "vphaddd" },
{ X86_INS_VPHADDSW, "vphaddsw" },
{ X86_INS_VPHADDUBD, "vphaddubd" },
{ X86_INS_VPHADDUBQ, "vphaddubq" },
{ X86_INS_VPHADDUBW, "vphaddubw" },
{ X86_INS_VPHADDUDQ, "vphaddudq" },
{ X86_INS_VPHADDUWD, "vphadduwd" },
{ X86_INS_VPHADDUWQ, "vphadduwq" },
{ X86_INS_VPHADDWD, "vphaddwd" },
{ X86_INS_VPHADDWQ, "vphaddwq" },
{ X86_INS_VPHADDW, "vphaddw" },
{ X86_INS_VPHMINPOSUW, "vphminposuw" },
{ X86_INS_VPHSUBBW, "vphsubbw" },
{ X86_INS_VPHSUBDQ, "vphsubdq" },
{ X86_INS_VPHSUBD, "vphsubd" },
{ X86_INS_VPHSUBSW, "vphsubsw" },
{ X86_INS_VPHSUBWD, "vphsubwd" },
{ X86_INS_VPHSUBW, "vphsubw" },
{ X86_INS_VPINSRB, "vpinsrb" },
{ X86_INS_VPINSRD, "vpinsrd" },
{ X86_INS_VPINSRQ, "vpinsrq" },
{ X86_INS_VPINSRW, "vpinsrw" },
{ X86_INS_VPLZCNTD, "vplzcntd" },
{ X86_INS_VPLZCNTQ, "vplzcntq" },
{ X86_INS_VPMACSDD, "vpmacsdd" },
{ X86_INS_VPMACSDQH, "vpmacsdqh" },
{ X86_INS_VPMACSDQL, "vpmacsdql" },
{ X86_INS_VPMACSSDD, "vpmacssdd" },
{ X86_INS_VPMACSSDQH, "vpmacssdqh" },
{ X86_INS_VPMACSSDQL, "vpmacssdql" },
{ X86_INS_VPMACSSWD, "vpmacsswd" },
{ X86_INS_VPMACSSWW, "vpmacssww" },
{ X86_INS_VPMACSWD, "vpmacswd" },
{ X86_INS_VPMACSWW, "vpmacsww" },
{ X86_INS_VPMADCSSWD, "vpmadcsswd" },
{ X86_INS_VPMADCSWD, "vpmadcswd" },
{ X86_INS_VPMADDUBSW, "vpmaddubsw" },
{ X86_INS_VPMADDWD, "vpmaddwd" },
{ X86_INS_VPMASKMOVD, "vpmaskmovd" },
{ X86_INS_VPMASKMOVQ, "vpmaskmovq" },
{ X86_INS_VPMAXSB, "vpmaxsb" },
{ X86_INS_VPMAXSD, "vpmaxsd" },
{ X86_INS_VPMAXSQ, "vpmaxsq" },
{ X86_INS_VPMAXSW, "vpmaxsw" },
{ X86_INS_VPMAXUB, "vpmaxub" },
{ X86_INS_VPMAXUD, "vpmaxud" },
{ X86_INS_VPMAXUQ, "vpmaxuq" },
{ X86_INS_VPMAXUW, "vpmaxuw" },
{ X86_INS_VPMINSB, "vpminsb" },
{ X86_INS_VPMINSD, "vpminsd" },
{ X86_INS_VPMINSQ, "vpminsq" },
{ X86_INS_VPMINSW, "vpminsw" },
{ X86_INS_VPMINUB, "vpminub" },
{ X86_INS_VPMINUD, "vpminud" },
{ X86_INS_VPMINUQ, "vpminuq" },
{ X86_INS_VPMINUW, "vpminuw" },
{ X86_INS_VPMOVDB, "vpmovdb" },
{ X86_INS_VPMOVDW, "vpmovdw" },
{ X86_INS_VPMOVM2B, "vpmovm2b" },
{ X86_INS_VPMOVM2D, "vpmovm2d" },
{ X86_INS_VPMOVM2Q, "vpmovm2q" },
{ X86_INS_VPMOVM2W, "vpmovm2w" },
{ X86_INS_VPMOVMSKB, "vpmovmskb" },
{ X86_INS_VPMOVQB, "vpmovqb" },
{ X86_INS_VPMOVQD, "vpmovqd" },
{ X86_INS_VPMOVQW, "vpmovqw" },
{ X86_INS_VPMOVSDB, "vpmovsdb" },
{ X86_INS_VPMOVSDW, "vpmovsdw" },
{ X86_INS_VPMOVSQB, "vpmovsqb" },
{ X86_INS_VPMOVSQD, "vpmovsqd" },
{ X86_INS_VPMOVSQW, "vpmovsqw" },
{ X86_INS_VPMOVSXBD, "vpmovsxbd" },
{ X86_INS_VPMOVSXBQ, "vpmovsxbq" },
{ X86_INS_VPMOVSXBW, "vpmovsxbw" },
{ X86_INS_VPMOVSXDQ, "vpmovsxdq" },
{ X86_INS_VPMOVSXWD, "vpmovsxwd" },
{ X86_INS_VPMOVSXWQ, "vpmovsxwq" },
{ X86_INS_VPMOVUSDB, "vpmovusdb" },
{ X86_INS_VPMOVUSDW, "vpmovusdw" },
{ X86_INS_VPMOVUSQB, "vpmovusqb" },
{ X86_INS_VPMOVUSQD, "vpmovusqd" },
{ X86_INS_VPMOVUSQW, "vpmovusqw" },
{ X86_INS_VPMOVZXBD, "vpmovzxbd" },
{ X86_INS_VPMOVZXBQ, "vpmovzxbq" },
{ X86_INS_VPMOVZXBW, "vpmovzxbw" },
{ X86_INS_VPMOVZXDQ, "vpmovzxdq" },
{ X86_INS_VPMOVZXWD, "vpmovzxwd" },
{ X86_INS_VPMOVZXWQ, "vpmovzxwq" },
{ X86_INS_VPMULDQ, "vpmuldq" },
{ X86_INS_VPMULHRSW, "vpmulhrsw" },
{ X86_INS_VPMULHUW, "vpmulhuw" },
{ X86_INS_VPMULHW, "vpmulhw" },
{ X86_INS_VPMULLD, "vpmulld" },
{ X86_INS_VPMULLQ, "vpmullq" },
{ X86_INS_VPMULLW, "vpmullw" },
{ X86_INS_VPMULUDQ, "vpmuludq" },
{ X86_INS_VPORD, "vpord" },
{ X86_INS_VPORQ, "vporq" },
{ X86_INS_VPOR, "vpor" },
{ X86_INS_VPPERM, "vpperm" },
{ X86_INS_VPROTB, "vprotb" },
{ X86_INS_VPROTD, "vprotd" },
{ X86_INS_VPROTQ, "vprotq" },
{ X86_INS_VPROTW, "vprotw" },
{ X86_INS_VPSADBW, "vpsadbw" },
{ X86_INS_VPSCATTERDD, "vpscatterdd" },
{ X86_INS_VPSCATTERDQ, "vpscatterdq" },
{ X86_INS_VPSCATTERQD, "vpscatterqd" },
{ X86_INS_VPSCATTERQQ, "vpscatterqq" },
{ X86_INS_VPSHAB, "vpshab" },
{ X86_INS_VPSHAD, "vpshad" },
{ X86_INS_VPSHAQ, "vpshaq" },
{ X86_INS_VPSHAW, "vpshaw" },
{ X86_INS_VPSHLB, "vpshlb" },
{ X86_INS_VPSHLD, "vpshld" },
{ X86_INS_VPSHLQ, "vpshlq" },
{ X86_INS_VPSHLW, "vpshlw" },
{ X86_INS_VPSHUFB, "vpshufb" },
{ X86_INS_VPSHUFD, "vpshufd" },
{ X86_INS_VPSHUFHW, "vpshufhw" },
{ X86_INS_VPSHUFLW, "vpshuflw" },
{ X86_INS_VPSIGNB, "vpsignb" },
{ X86_INS_VPSIGND, "vpsignd" },
{ X86_INS_VPSIGNW, "vpsignw" },
{ X86_INS_VPSLLDQ, "vpslldq" },
{ X86_INS_VPSLLD, "vpslld" },
{ X86_INS_VPSLLQ, "vpsllq" },
{ X86_INS_VPSLLVD, "vpsllvd" },
{ X86_INS_VPSLLVQ, "vpsllvq" },
{ X86_INS_VPSLLW, "vpsllw" },
{ X86_INS_VPSRAD, "vpsrad" },
{ X86_INS_VPSRAQ, "vpsraq" },
{ X86_INS_VPSRAVD, "vpsravd" },
{ X86_INS_VPSRAVQ, "vpsravq" },
{ X86_INS_VPSRAW, "vpsraw" },
{ X86_INS_VPSRLDQ, "vpsrldq" },
{ X86_INS_VPSRLD, "vpsrld" },
{ X86_INS_VPSRLQ, "vpsrlq" },
{ X86_INS_VPSRLVD, "vpsrlvd" },
{ X86_INS_VPSRLVQ, "vpsrlvq" },
{ X86_INS_VPSRLW, "vpsrlw" },
{ X86_INS_VPSUBB, "vpsubb" },
{ X86_INS_VPSUBD, "vpsubd" },
{ X86_INS_VPSUBQ, "vpsubq" },
{ X86_INS_VPSUBSB, "vpsubsb" },
{ X86_INS_VPSUBSW, "vpsubsw" },
{ X86_INS_VPSUBUSB, "vpsubusb" },
{ X86_INS_VPSUBUSW, "vpsubusw" },
{ X86_INS_VPSUBW, "vpsubw" },
{ X86_INS_VPTESTMD, "vptestmd" },
{ X86_INS_VPTESTMQ, "vptestmq" },
{ X86_INS_VPTESTNMD, "vptestnmd" },
{ X86_INS_VPTESTNMQ, "vptestnmq" },
{ X86_INS_VPTEST, "vptest" },
{ X86_INS_VPUNPCKHBW, "vpunpckhbw" },
{ X86_INS_VPUNPCKHDQ, "vpunpckhdq" },
{ X86_INS_VPUNPCKHQDQ, "vpunpckhqdq" },
{ X86_INS_VPUNPCKHWD, "vpunpckhwd" },
{ X86_INS_VPUNPCKLBW, "vpunpcklbw" },
{ X86_INS_VPUNPCKLDQ, "vpunpckldq" },
{ X86_INS_VPUNPCKLQDQ, "vpunpcklqdq" },
{ X86_INS_VPUNPCKLWD, "vpunpcklwd" },
{ X86_INS_VPXORD, "vpxord" },
{ X86_INS_VPXORQ, "vpxorq" },
{ X86_INS_VPXOR, "vpxor" },
{ X86_INS_VRCP14PD, "vrcp14pd" },
{ X86_INS_VRCP14PS, "vrcp14ps" },
{ X86_INS_VRCP14SD, "vrcp14sd" },
{ X86_INS_VRCP14SS, "vrcp14ss" },
{ X86_INS_VRCP28PD, "vrcp28pd" },
{ X86_INS_VRCP28PS, "vrcp28ps" },
{ X86_INS_VRCP28SD, "vrcp28sd" },
{ X86_INS_VRCP28SS, "vrcp28ss" },
{ X86_INS_VRCPPS, "vrcpps" },
{ X86_INS_VRCPSS, "vrcpss" },
{ X86_INS_VRNDSCALEPD, "vrndscalepd" },
{ X86_INS_VRNDSCALEPS, "vrndscaleps" },
{ X86_INS_VRNDSCALESD, "vrndscalesd" },
{ X86_INS_VRNDSCALESS, "vrndscaless" },
{ X86_INS_VROUNDPD, "vroundpd" },
{ X86_INS_VROUNDPS, "vroundps" },
{ X86_INS_VROUNDSD, "vroundsd" },
{ X86_INS_VROUNDSS, "vroundss" },
{ X86_INS_VRSQRT14PD, "vrsqrt14pd" },
{ X86_INS_VRSQRT14PS, "vrsqrt14ps" },
{ X86_INS_VRSQRT14SD, "vrsqrt14sd" },
{ X86_INS_VRSQRT14SS, "vrsqrt14ss" },
{ X86_INS_VRSQRT28PD, "vrsqrt28pd" },
{ X86_INS_VRSQRT28PS, "vrsqrt28ps" },
{ X86_INS_VRSQRT28SD, "vrsqrt28sd" },
{ X86_INS_VRSQRT28SS, "vrsqrt28ss" },
{ X86_INS_VRSQRTPS, "vrsqrtps" },
{ X86_INS_VRSQRTSS, "vrsqrtss" },
{ X86_INS_VSCATTERDPD, "vscatterdpd" },
{ X86_INS_VSCATTERDPS, "vscatterdps" },
{ X86_INS_VSCATTERPF0DPD, "vscatterpf0dpd" },
{ X86_INS_VSCATTERPF0DPS, "vscatterpf0dps" },
{ X86_INS_VSCATTERPF0QPD, "vscatterpf0qpd" },
{ X86_INS_VSCATTERPF0QPS, "vscatterpf0qps" },
{ X86_INS_VSCATTERPF1DPD, "vscatterpf1dpd" },
{ X86_INS_VSCATTERPF1DPS, "vscatterpf1dps" },
{ X86_INS_VSCATTERPF1QPD, "vscatterpf1qpd" },
{ X86_INS_VSCATTERPF1QPS, "vscatterpf1qps" },
{ X86_INS_VSCATTERQPD, "vscatterqpd" },
{ X86_INS_VSCATTERQPS, "vscatterqps" },
{ X86_INS_VSHUFPD, "vshufpd" },
{ X86_INS_VSHUFPS, "vshufps" },
{ X86_INS_VSQRTPD, "vsqrtpd" },
{ X86_INS_VSQRTPS, "vsqrtps" },
{ X86_INS_VSQRTSD, "vsqrtsd" },
{ X86_INS_VSQRTSS, "vsqrtss" },
{ X86_INS_VSTMXCSR, "vstmxcsr" },
{ X86_INS_VSUBPD, "vsubpd" },
{ X86_INS_VSUBPS, "vsubps" },
{ X86_INS_VSUBSD, "vsubsd" },
{ X86_INS_VSUBSS, "vsubss" },
{ X86_INS_VTESTPD, "vtestpd" },
{ X86_INS_VTESTPS, "vtestps" },
{ X86_INS_VUNPCKHPD, "vunpckhpd" },
{ X86_INS_VUNPCKHPS, "vunpckhps" },
{ X86_INS_VUNPCKLPD, "vunpcklpd" },
{ X86_INS_VUNPCKLPS, "vunpcklps" },
{ X86_INS_VZEROALL, "vzeroall" },
{ X86_INS_VZEROUPPER, "vzeroupper" },
{ X86_INS_WAIT, "wait" },
{ X86_INS_WBINVD, "wbinvd" },
{ X86_INS_WRFSBASE, "wrfsbase" },
{ X86_INS_WRGSBASE, "wrgsbase" },
{ X86_INS_WRMSR, "wrmsr" },
{ X86_INS_XABORT, "xabort" },
{ X86_INS_XACQUIRE, "xacquire" },
{ X86_INS_XBEGIN, "xbegin" },
{ X86_INS_XCHG, "xchg" },
{ X86_INS_XCRYPTCBC, "xcryptcbc" },
{ X86_INS_XCRYPTCFB, "xcryptcfb" },
{ X86_INS_XCRYPTCTR, "xcryptctr" },
{ X86_INS_XCRYPTECB, "xcryptecb" },
{ X86_INS_XCRYPTOFB, "xcryptofb" },
{ X86_INS_XEND, "xend" },
{ X86_INS_XGETBV, "xgetbv" },
{ X86_INS_XLATB, "xlatb" },
{ X86_INS_XRELEASE, "xrelease" },
{ X86_INS_XRSTOR, "xrstor" },
{ X86_INS_XRSTOR64, "xrstor64" },
{ X86_INS_XRSTORS, "xrstors" },
{ X86_INS_XRSTORS64, "xrstors64" },
{ X86_INS_XSAVE, "xsave" },
{ X86_INS_XSAVE64, "xsave64" },
{ X86_INS_XSAVEC, "xsavec" },
{ X86_INS_XSAVEC64, "xsavec64" },
{ X86_INS_XSAVEOPT, "xsaveopt" },
{ X86_INS_XSAVEOPT64, "xsaveopt64" },
{ X86_INS_XSAVES, "xsaves" },
{ X86_INS_XSAVES64, "xsaves64" },
{ X86_INS_XSETBV, "xsetbv" },
{ X86_INS_XSHA1, "xsha1" },
{ X86_INS_XSHA256, "xsha256" },
{ X86_INS_XSTORE, "xstore" },
{ X86_INS_XTEST, "xtest" },
{ X86_INS_FDISI8087_NOP, "fdisi8087_nop" },
{ X86_INS_FENI8087_NOP, "feni8087_nop" },
// pseudo instructions
{ X86_INS_CMPSS, "cmpss" },
{ X86_INS_CMPEQSS, "cmpeqss" },
{ X86_INS_CMPLTSS, "cmpltss" },
{ X86_INS_CMPLESS, "cmpless" },
{ X86_INS_CMPUNORDSS, "cmpunordss" },
{ X86_INS_CMPNEQSS, "cmpneqss" },
{ X86_INS_CMPNLTSS, "cmpnltss" },
{ X86_INS_CMPNLESS, "cmpnless" },
{ X86_INS_CMPORDSS, "cmpordss" },
{ X86_INS_CMPSD, "cmpsd" },
{ X86_INS_CMPEQSD, "cmpeqsd" },
{ X86_INS_CMPLTSD, "cmpltsd" },
{ X86_INS_CMPLESD, "cmplesd" },
{ X86_INS_CMPUNORDSD, "cmpunordsd" },
{ X86_INS_CMPNEQSD, "cmpneqsd" },
{ X86_INS_CMPNLTSD, "cmpnltsd" },
{ X86_INS_CMPNLESD, "cmpnlesd" },
{ X86_INS_CMPORDSD, "cmpordsd" },
{ X86_INS_CMPPS, "cmpps" },
{ X86_INS_CMPEQPS, "cmpeqps" },
{ X86_INS_CMPLTPS, "cmpltps" },
{ X86_INS_CMPLEPS, "cmpleps" },
{ X86_INS_CMPUNORDPS, "cmpunordps" },
{ X86_INS_CMPNEQPS, "cmpneqps" },
{ X86_INS_CMPNLTPS, "cmpnltps" },
{ X86_INS_CMPNLEPS, "cmpnleps" },
{ X86_INS_CMPORDPS, "cmpordps" },
{ X86_INS_CMPPD, "cmppd" },
{ X86_INS_CMPEQPD, "cmpeqpd" },
{ X86_INS_CMPLTPD, "cmpltpd" },
{ X86_INS_CMPLEPD, "cmplepd" },
{ X86_INS_CMPUNORDPD, "cmpunordpd" },
{ X86_INS_CMPNEQPD, "cmpneqpd" },
{ X86_INS_CMPNLTPD, "cmpnltpd" },
{ X86_INS_CMPNLEPD, "cmpnlepd" },
{ X86_INS_CMPORDPD, "cmpordpd" },
{ X86_INS_VCMPSS, "vcmpss" },
{ X86_INS_VCMPEQSS, "vcmpeqss" },
{ X86_INS_VCMPLTSS, "vcmpltss" },
{ X86_INS_VCMPLESS, "vcmpless" },
{ X86_INS_VCMPUNORDSS, "vcmpunordss" },
{ X86_INS_VCMPNEQSS, "vcmpneqss" },
{ X86_INS_VCMPNLTSS, "vcmpnltss" },
{ X86_INS_VCMPNLESS, "vcmpnless" },
{ X86_INS_VCMPORDSS, "vcmpordss" },
{ X86_INS_VCMPEQ_UQSS, "vcmpeq_uqss" },
{ X86_INS_VCMPNGESS, "vcmpngess" },
{ X86_INS_VCMPNGTSS, "vcmpngtss" },
{ X86_INS_VCMPFALSESS, "vcmpfalsess" },
{ X86_INS_VCMPNEQ_OQSS, "vcmpneq_oqss" },
{ X86_INS_VCMPGESS, "vcmpgess" },
{ X86_INS_VCMPGTSS, "vcmpgtss" },
{ X86_INS_VCMPTRUESS, "vcmptruess" },
{ X86_INS_VCMPEQ_OSSS, "vcmpeq_osss" },
{ X86_INS_VCMPLT_OQSS, "vcmplt_oqss" },
{ X86_INS_VCMPLE_OQSS, "vcmple_oqss" },
{ X86_INS_VCMPUNORD_SSS, "vcmpunord_sss" },
{ X86_INS_VCMPNEQ_USSS, "vcmpneq_usss" },
{ X86_INS_VCMPNLT_UQSS, "vcmpnlt_uqss" },
{ X86_INS_VCMPNLE_UQSS, "vcmpnle_uqss" },
{ X86_INS_VCMPORD_SSS, "vcmpord_sss" },
{ X86_INS_VCMPEQ_USSS, "vcmpeq_usss" },
{ X86_INS_VCMPNGE_UQSS, "vcmpnge_uqss" },
{ X86_INS_VCMPNGT_UQSS, "vcmpngt_uqss" },
{ X86_INS_VCMPFALSE_OSSS, "vcmpfalse_osss" },
{ X86_INS_VCMPNEQ_OSSS, "vcmpneq_osss" },
{ X86_INS_VCMPGE_OQSS, "vcmpge_oqss" },
{ X86_INS_VCMPGT_OQSS, "vcmpgt_oqss" },
{ X86_INS_VCMPTRUE_USSS, "vcmptrue_usss" },
{ X86_INS_VCMPSD, "vcmpsd" },
{ X86_INS_VCMPEQSD, "vcmpeqsd" },
{ X86_INS_VCMPLTSD, "vcmpltsd" },
{ X86_INS_VCMPLESD, "vcmplesd" },
{ X86_INS_VCMPUNORDSD, "vcmpunordsd" },
{ X86_INS_VCMPNEQSD, "vcmpneqsd" },
{ X86_INS_VCMPNLTSD, "vcmpnltsd" },
{ X86_INS_VCMPNLESD, "vcmpnlesd" },
{ X86_INS_VCMPORDSD, "vcmpordsd" },
{ X86_INS_VCMPEQ_UQSD, "vcmpeq_uqsd" },
{ X86_INS_VCMPNGESD, "vcmpngesd" },
{ X86_INS_VCMPNGTSD, "vcmpngtsd" },
{ X86_INS_VCMPFALSESD, "vcmpfalsesd" },
{ X86_INS_VCMPNEQ_OQSD, "vcmpneq_oqsd" },
{ X86_INS_VCMPGESD, "vcmpgesd" },
{ X86_INS_VCMPGTSD, "vcmpgtsd" },
{ X86_INS_VCMPTRUESD, "vcmptruesd" },
{ X86_INS_VCMPEQ_OSSD, "vcmpeq_ossd" },
{ X86_INS_VCMPLT_OQSD, "vcmplt_oqsd" },
{ X86_INS_VCMPLE_OQSD, "vcmple_oqsd" },
{ X86_INS_VCMPUNORD_SSD, "vcmpunord_ssd" },
{ X86_INS_VCMPNEQ_USSD, "vcmpneq_ussd" },
{ X86_INS_VCMPNLT_UQSD, "vcmpnlt_uqsd" },
{ X86_INS_VCMPNLE_UQSD, "vcmpnle_uqsd" },
{ X86_INS_VCMPORD_SSD, "vcmpord_ssd" },
{ X86_INS_VCMPEQ_USSD, "vcmpeq_ussd" },
{ X86_INS_VCMPNGE_UQSD, "vcmpnge_uqsd" },
{ X86_INS_VCMPNGT_UQSD, "vcmpngt_uqsd" },
{ X86_INS_VCMPFALSE_OSSD, "vcmpfalse_ossd" },
{ X86_INS_VCMPNEQ_OSSD, "vcmpneq_ossd" },
{ X86_INS_VCMPGE_OQSD, "vcmpge_oqsd" },
{ X86_INS_VCMPGT_OQSD, "vcmpgt_oqsd" },
{ X86_INS_VCMPTRUE_USSD, "vcmptrue_ussd" },
{ X86_INS_VCMPPS, "vcmpps" },
{ X86_INS_VCMPEQPS, "vcmpeqps" },
{ X86_INS_VCMPLTPS, "vcmpltps" },
{ X86_INS_VCMPLEPS, "vcmpleps" },
{ X86_INS_VCMPUNORDPS, "vcmpunordps" },
{ X86_INS_VCMPNEQPS, "vcmpneqps" },
{ X86_INS_VCMPNLTPS, "vcmpnltps" },
{ X86_INS_VCMPNLEPS, "vcmpnleps" },
{ X86_INS_VCMPORDPS, "vcmpordps" },
{ X86_INS_VCMPEQ_UQPS, "vcmpeq_uqps" },
{ X86_INS_VCMPNGEPS, "vcmpngeps" },
{ X86_INS_VCMPNGTPS, "vcmpngtps" },
{ X86_INS_VCMPFALSEPS, "vcmpfalseps" },
{ X86_INS_VCMPNEQ_OQPS, "vcmpneq_oqps" },
{ X86_INS_VCMPGEPS, "vcmpgeps" },
{ X86_INS_VCMPGTPS, "vcmpgtps" },
{ X86_INS_VCMPTRUEPS, "vcmptrueps" },
{ X86_INS_VCMPEQ_OSPS, "vcmpeq_osps" },
{ X86_INS_VCMPLT_OQPS, "vcmplt_oqps" },
{ X86_INS_VCMPLE_OQPS, "vcmple_oqps" },
{ X86_INS_VCMPUNORD_SPS, "vcmpunord_sps" },
{ X86_INS_VCMPNEQ_USPS, "vcmpneq_usps" },
{ X86_INS_VCMPNLT_UQPS, "vcmpnlt_uqps" },
{ X86_INS_VCMPNLE_UQPS, "vcmpnle_uqps" },
{ X86_INS_VCMPORD_SPS, "vcmpord_sps" },
{ X86_INS_VCMPEQ_USPS, "vcmpeq_usps" },
{ X86_INS_VCMPNGE_UQPS, "vcmpnge_uqps" },
{ X86_INS_VCMPNGT_UQPS, "vcmpngt_uqps" },
{ X86_INS_VCMPFALSE_OSPS, "vcmpfalse_osps" },
{ X86_INS_VCMPNEQ_OSPS, "vcmpneq_osps" },
{ X86_INS_VCMPGE_OQPS, "vcmpge_oqps" },
{ X86_INS_VCMPGT_OQPS, "vcmpgt_oqps" },
{ X86_INS_VCMPTRUE_USPS, "vcmptrue_usps" },
{ X86_INS_VCMPPD, "vcmppd" },
{ X86_INS_VCMPEQPD, "vcmpeqpd" },
{ X86_INS_VCMPLTPD, "vcmpltpd" },
{ X86_INS_VCMPLEPD, "vcmplepd" },
{ X86_INS_VCMPUNORDPD, "vcmpunordpd" },
{ X86_INS_VCMPNEQPD, "vcmpneqpd" },
{ X86_INS_VCMPNLTPD, "vcmpnltpd" },
{ X86_INS_VCMPNLEPD, "vcmpnlepd" },
{ X86_INS_VCMPORDPD, "vcmpordpd" },
{ X86_INS_VCMPEQ_UQPD, "vcmpeq_uqpd" },
{ X86_INS_VCMPNGEPD, "vcmpngepd" },
{ X86_INS_VCMPNGTPD, "vcmpngtpd" },
{ X86_INS_VCMPFALSEPD, "vcmpfalsepd" },
{ X86_INS_VCMPNEQ_OQPD, "vcmpneq_oqpd" },
{ X86_INS_VCMPGEPD, "vcmpgepd" },
{ X86_INS_VCMPGTPD, "vcmpgtpd" },
{ X86_INS_VCMPTRUEPD, "vcmptruepd" },
{ X86_INS_VCMPEQ_OSPD, "vcmpeq_ospd" },
{ X86_INS_VCMPLT_OQPD, "vcmplt_oqpd" },
{ X86_INS_VCMPLE_OQPD, "vcmple_oqpd" },
{ X86_INS_VCMPUNORD_SPD, "vcmpunord_spd" },
{ X86_INS_VCMPNEQ_USPD, "vcmpneq_uspd" },
{ X86_INS_VCMPNLT_UQPD, "vcmpnlt_uqpd" },
{ X86_INS_VCMPNLE_UQPD, "vcmpnle_uqpd" },
{ X86_INS_VCMPORD_SPD, "vcmpord_spd" },
{ X86_INS_VCMPEQ_USPD, "vcmpeq_uspd" },
{ X86_INS_VCMPNGE_UQPD, "vcmpnge_uqpd" },
{ X86_INS_VCMPNGT_UQPD, "vcmpngt_uqpd" },
{ X86_INS_VCMPFALSE_OSPD, "vcmpfalse_ospd" },
{ X86_INS_VCMPNEQ_OSPD, "vcmpneq_ospd" },
{ X86_INS_VCMPGE_OQPD, "vcmpge_oqpd" },
{ X86_INS_VCMPGT_OQPD, "vcmpgt_oqpd" },
{ X86_INS_VCMPTRUE_USPD, "vcmptrue_uspd" },
};
#endif
const char *X86_insn_name(csh handle, unsigned int id)
{
#ifndef CAPSTONE_DIET
if (id >= X86_INS_ENDING)
return NULL;
return insn_name_maps[id].name;
#else
return NULL;
#endif
}
#ifndef CAPSTONE_DIET
static name_map group_name_maps[] = {
// generic groups
{ X86_GRP_INVALID, NULL },
{ X86_GRP_JUMP, "jump" },
{ X86_GRP_CALL, "call" },
{ X86_GRP_RET, "ret" },
{ X86_GRP_INT, "int" },
{ X86_GRP_IRET, "iret" },
{ X86_GRP_PRIVILEGE, "privilege" },
// architecture-specific groups
{ X86_GRP_VM, "vm" },
{ X86_GRP_3DNOW, "3dnow" },
{ X86_GRP_AES, "aes" },
{ X86_GRP_ADX, "adx" },
{ X86_GRP_AVX, "avx" },
{ X86_GRP_AVX2, "avx2" },
{ X86_GRP_AVX512, "avx512" },
{ X86_GRP_BMI, "bmi" },
{ X86_GRP_BMI2, "bmi2" },
{ X86_GRP_CMOV, "cmov" },
{ X86_GRP_F16C, "fc16" },
{ X86_GRP_FMA, "fma" },
{ X86_GRP_FMA4, "fma4" },
{ X86_GRP_FSGSBASE, "fsgsbase" },
{ X86_GRP_HLE, "hle" },
{ X86_GRP_MMX, "mmx" },
{ X86_GRP_MODE32, "mode32" },
{ X86_GRP_MODE64, "mode64" },
{ X86_GRP_RTM, "rtm" },
{ X86_GRP_SHA, "sha" },
{ X86_GRP_SSE1, "sse1" },
{ X86_GRP_SSE2, "sse2" },
{ X86_GRP_SSE3, "sse3" },
{ X86_GRP_SSE41, "sse41" },
{ X86_GRP_SSE42, "sse42" },
{ X86_GRP_SSE4A, "sse4a" },
{ X86_GRP_SSSE3, "ssse3" },
{ X86_GRP_PCLMUL, "pclmul" },
{ X86_GRP_XOP, "xop" },
{ X86_GRP_CDI, "cdi" },
{ X86_GRP_ERI, "eri" },
{ X86_GRP_TBM, "tbm" },
{ X86_GRP_16BITMODE, "16bitmode" },
{ X86_GRP_NOT64BITMODE, "not64bitmode" },
{ X86_GRP_SGX, "sgx" },
{ X86_GRP_DQI, "dqi" },
{ X86_GRP_BWI, "bwi" },
{ X86_GRP_PFI, "pfi" },
{ X86_GRP_VLX, "vlx" },
{ X86_GRP_SMAP, "smap" },
{ X86_GRP_NOVLX, "novlx" },
};
#endif
const char *X86_group_name(csh handle, unsigned int id)
{
#ifndef CAPSTONE_DIET
return id2name(group_name_maps, ARR_SIZE(group_name_maps), id);
#else
return NULL;
#endif
}
#define GET_INSTRINFO_ENUM
#ifdef CAPSTONE_X86_REDUCE
#include "X86GenInstrInfo_reduce.inc"
#else
#include "X86GenInstrInfo.inc"
#endif
#ifndef CAPSTONE_X86_REDUCE
static insn_map insns[] = { // full x86 instructions
// dummy item
{
0, 0,
#ifndef CAPSTONE_DIET
{ 0 }, { 0 }, { 0 }, 0, 0
#endif
},
#include "X86MappingInsn.inc"
};
#else // X86 reduce (defined CAPSTONE_X86_REDUCE)
static insn_map insns[] = { // reduce x86 instructions
// dummy item
{
0, 0,
#ifndef CAPSTONE_DIET
{ 0 }, { 0 }, { 0 }, 0, 0
#endif
},
#include "X86MappingInsn_reduce.inc"
};
#endif
#ifndef CAPSTONE_DIET
// replace r1 = r2
static void arr_replace(uint16_t *arr, uint8_t max, x86_reg r1, x86_reg r2)
{
uint8_t i;
for(i = 0; i < max; i++) {
if (arr[i] == r1) {
arr[i] = r2;
break;
}
}
}
#endif
// given internal insn id, return public instruction info
void X86_get_insn_id(cs_struct *h, cs_insn *insn, unsigned int id)
{
int i = insn_find(insns, ARR_SIZE(insns), id, &h->insn_cache);
if (i != 0) {
insn->id = insns[i].mapid;
if (h->detail) {
#ifndef CAPSTONE_DIET
memcpy(insn->detail->regs_read, insns[i].regs_use, sizeof(insns[i].regs_use));
insn->detail->regs_read_count = (uint8_t)count_positive(insns[i].regs_use);
// special cases when regs_write[] depends on arch
switch(id) {
default:
memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod));
insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod);
break;
case X86_RDTSC:
if (h->mode == CS_MODE_64) {
memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod));
insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod);
} else {
insn->detail->regs_write[0] = X86_REG_EAX;
insn->detail->regs_write[1] = X86_REG_EDX;
insn->detail->regs_write_count = 2;
}
break;
case X86_RDTSCP:
if (h->mode == CS_MODE_64) {
memcpy(insn->detail->regs_write, insns[i].regs_mod, sizeof(insns[i].regs_mod));
insn->detail->regs_write_count = (uint8_t)count_positive(insns[i].regs_mod);
} else {
insn->detail->regs_write[0] = X86_REG_EAX;
insn->detail->regs_write[1] = X86_REG_ECX;
insn->detail->regs_write[2] = X86_REG_EDX;
insn->detail->regs_write_count = 3;
}
break;
}
switch(insn->id) {
default:
break;
case X86_INS_LOOP:
case X86_INS_LOOPE:
case X86_INS_LOOPNE:
switch(h->mode) {
default: break;
case CS_MODE_16:
insn->detail->regs_read[0] = X86_REG_CX;
insn->detail->regs_read_count = 1;
insn->detail->regs_write[0] = X86_REG_CX;
insn->detail->regs_write_count = 1;
break;
case CS_MODE_32:
insn->detail->regs_read[0] = X86_REG_ECX;
insn->detail->regs_read_count = 1;
insn->detail->regs_write[0] = X86_REG_ECX;
insn->detail->regs_write_count = 1;
break;
case CS_MODE_64:
insn->detail->regs_read[0] = X86_REG_RCX;
insn->detail->regs_read_count = 1;
insn->detail->regs_write[0] = X86_REG_RCX;
insn->detail->regs_write_count = 1;
break;
}
// LOOPE & LOOPNE also read EFLAGS
if (insn->id != X86_INS_LOOP) {
insn->detail->regs_read[1] = X86_REG_EFLAGS;
insn->detail->regs_read_count = 2;
}
break;
case X86_INS_LODSB:
case X86_INS_LODSD:
case X86_INS_LODSQ:
case X86_INS_LODSW:
switch(h->mode) {
default:
break;
case CS_MODE_16:
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_SI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_SI);
break;
case CS_MODE_64:
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_RSI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_RSI);
break;
}
break;
case X86_INS_SCASB:
case X86_INS_SCASW:
case X86_INS_SCASQ:
case X86_INS_STOSB:
case X86_INS_STOSD:
case X86_INS_STOSQ:
case X86_INS_STOSW:
switch(h->mode) {
default:
break;
case CS_MODE_16:
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_DI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_DI);
break;
case CS_MODE_64:
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_RDI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_RDI);
break;
}
break;
case X86_INS_CMPSB:
case X86_INS_CMPSD:
case X86_INS_CMPSQ:
case X86_INS_CMPSW:
case X86_INS_MOVSB:
case X86_INS_MOVSW:
case X86_INS_MOVSD:
case X86_INS_MOVSQ:
switch(h->mode) {
default:
break;
case CS_MODE_16:
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_DI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_DI);
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_SI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_SI);
break;
case CS_MODE_64:
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_EDI, X86_REG_RDI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_EDI, X86_REG_RDI);
arr_replace(insn->detail->regs_read, insn->detail->regs_read_count, X86_REG_ESI, X86_REG_RSI);
arr_replace(insn->detail->regs_write, insn->detail->regs_write_count, X86_REG_ESI, X86_REG_RSI);
break;
}
break;
}
memcpy(insn->detail->groups, insns[i].groups, sizeof(insns[i].groups));
insn->detail->groups_count = (uint8_t)count_positive8(insns[i].groups);
if (insns[i].branch || insns[i].indirect_branch) {
// this insn also belongs to JUMP group. add JUMP group
insn->detail->groups[insn->detail->groups_count] = X86_GRP_JUMP;
insn->detail->groups_count++;
}
switch (insns[i].id) {
case X86_OUT8ir:
case X86_OUT16ir:
case X86_OUT32ir:
if (insn->detail->x86.operands[0].imm == -78) {
// Writing to port 0xb2 causes an SMI on most platforms
// See: http://cs.gmu.edu/~tr-admin/papers/GMU-CS-TR-2011-8.pdf
insn->detail->groups[insn->detail->groups_count] = X86_GRP_INT;
insn->detail->groups_count++;
}
break;
default:
break;
}
#endif
}
}
}
// map special instructions with accumulate registers.
// this is needed because LLVM embeds these register names into AsmStrs[],
// but not separately in operands
struct insn_reg {
uint16_t insn;
x86_reg reg;
enum cs_ac_type access;
};
struct insn_reg2 {
uint16_t insn;
x86_reg reg1, reg2;
enum cs_ac_type access1, access2;
};
static struct insn_reg insn_regs_att[] = {
{ X86_INSB, X86_REG_DX },
{ X86_INSW, X86_REG_DX },
{ X86_INSL, X86_REG_DX },
{ X86_MOV64o64a, X86_REG_RAX },
{ X86_MOV32o32a, X86_REG_EAX },
{ X86_MOV64o32a, X86_REG_EAX },
{ X86_MOV16o16a, X86_REG_AX },
{ X86_PUSHCS32, X86_REG_CS },
{ X86_PUSHDS32, X86_REG_DS },
{ X86_PUSHES32, X86_REG_ES },
{ X86_PUSHFS32, X86_REG_FS },
{ X86_PUSHGS32, X86_REG_GS },
{ X86_PUSHSS32, X86_REG_SS },
{ X86_PUSHFS64, X86_REG_FS },
{ X86_PUSHGS64, X86_REG_GS },
{ X86_PUSHCS16, X86_REG_CS },
{ X86_PUSHDS16, X86_REG_DS },
{ X86_PUSHES16, X86_REG_ES },
{ X86_PUSHFS16, X86_REG_FS },
{ X86_PUSHGS16, X86_REG_GS },
{ X86_PUSHSS16, X86_REG_SS },
{ X86_POPDS32, X86_REG_DS },
{ X86_POPES32, X86_REG_ES },
{ X86_POPFS32, X86_REG_FS },
{ X86_POPGS32, X86_REG_GS },
{ X86_POPSS32, X86_REG_SS },
{ X86_POPFS64, X86_REG_FS },
{ X86_POPGS64, X86_REG_GS },
{ X86_POPDS16, X86_REG_DS },
{ X86_POPES16, X86_REG_ES },
{ X86_POPFS16, X86_REG_FS },
{ X86_POPGS16, X86_REG_GS },
{ X86_POPSS16, X86_REG_SS },
{ X86_RCL32rCL, X86_REG_CL },
{ X86_SHL8rCL, X86_REG_CL },
{ X86_SHL16rCL, X86_REG_CL },
{ X86_SHL32rCL, X86_REG_CL },
{ X86_SHL64rCL, X86_REG_CL },
{ X86_SAL8rCL, X86_REG_CL },
{ X86_SAL16rCL, X86_REG_CL },
{ X86_SAL32rCL, X86_REG_CL },
{ X86_SAL64rCL, X86_REG_CL },
{ X86_SHR8rCL, X86_REG_CL },
{ X86_SHR16rCL, X86_REG_CL },
{ X86_SHR32rCL, X86_REG_CL },
{ X86_SHR64rCL, X86_REG_CL },
{ X86_SAR8rCL, X86_REG_CL },
{ X86_SAR16rCL, X86_REG_CL },
{ X86_SAR32rCL, X86_REG_CL },
{ X86_SAR64rCL, X86_REG_CL },
{ X86_RCL8rCL, X86_REG_CL },
{ X86_RCL16rCL, X86_REG_CL },
{ X86_RCL32rCL, X86_REG_CL },
{ X86_RCL64rCL, X86_REG_CL },
{ X86_RCR8rCL, X86_REG_CL },
{ X86_RCR16rCL, X86_REG_CL },
{ X86_RCR32rCL, X86_REG_CL },
{ X86_RCR64rCL, X86_REG_CL },
{ X86_ROL8rCL, X86_REG_CL },
{ X86_ROL16rCL, X86_REG_CL },
{ X86_ROL32rCL, X86_REG_CL },
{ X86_ROL64rCL, X86_REG_CL },
{ X86_ROR8rCL, X86_REG_CL },
{ X86_ROR16rCL, X86_REG_CL },
{ X86_ROR32rCL, X86_REG_CL },
{ X86_ROR64rCL, X86_REG_CL },
{ X86_SHLD16rrCL, X86_REG_CL },
{ X86_SHRD16rrCL, X86_REG_CL },
{ X86_SHLD32rrCL, X86_REG_CL },
{ X86_SHRD32rrCL, X86_REG_CL },
{ X86_SHLD64rrCL, X86_REG_CL },
{ X86_SHRD64rrCL, X86_REG_CL },
{ X86_SHLD16mrCL, X86_REG_CL },
{ X86_SHRD16mrCL, X86_REG_CL },
{ X86_SHLD32mrCL, X86_REG_CL },
{ X86_SHRD32mrCL, X86_REG_CL },
{ X86_SHLD64mrCL, X86_REG_CL },
{ X86_SHRD64mrCL, X86_REG_CL },
{ X86_OUT8ir, X86_REG_AL },
{ X86_OUT16ir, X86_REG_AX },
{ X86_OUT32ir, X86_REG_EAX },
#ifndef CAPSTONE_X86_REDUCE
{ X86_SKINIT, X86_REG_EAX },
{ X86_VMRUN32, X86_REG_EAX },
{ X86_VMRUN64, X86_REG_RAX },
{ X86_VMLOAD32, X86_REG_EAX },
{ X86_VMLOAD64, X86_REG_RAX },
{ X86_VMSAVE32, X86_REG_EAX },
{ X86_VMSAVE64, X86_REG_RAX },
{ X86_FNSTSW16r, X86_REG_AX },
{ X86_ADD_FrST0, X86_REG_ST0 },
{ X86_SUB_FrST0, X86_REG_ST0 },
{ X86_SUBR_FrST0, X86_REG_ST0 },
{ X86_MUL_FrST0, X86_REG_ST0 },
{ X86_DIV_FrST0, X86_REG_ST0 },
{ X86_DIVR_FrST0, X86_REG_ST0 },
#endif
};
static struct insn_reg insn_regs_intel[] = {
{ X86_OUTSB, X86_REG_DX, CS_AC_WRITE },
{ X86_OUTSW, X86_REG_DX, CS_AC_WRITE },
{ X86_OUTSL, X86_REG_DX, CS_AC_WRITE },
{ X86_MOV8ao16, X86_REG_AL, CS_AC_WRITE }, // 16-bit A0 1020 // mov al, byte ptr [0x2010]
{ X86_MOV8ao32, X86_REG_AL, CS_AC_WRITE }, // 32-bit A0 10203040 // mov al, byte ptr [0x40302010]
{ X86_MOV8ao64, X86_REG_AL, CS_AC_WRITE }, // 64-bit 66 A0 1020304050607080 // movabs al, byte ptr [0x8070605040302010]
{ X86_MOV16ao16, X86_REG_AX, CS_AC_WRITE }, // 16-bit A1 1020 // mov ax, word ptr [0x2010]
{ X86_MOV16ao32, X86_REG_AX, CS_AC_WRITE }, // 32-bit A1 10203040 // mov ax, word ptr [0x40302010]
{ X86_MOV16ao64, X86_REG_AX, CS_AC_WRITE }, // 64-bit 66 A1 1020304050607080 // movabs ax, word ptr [0x8070605040302010]
{ X86_MOV32ao16, X86_REG_EAX, CS_AC_WRITE }, // 32-bit 67 A1 1020 // mov eax, dword ptr [0x2010]
{ X86_MOV32ao32, X86_REG_EAX, CS_AC_WRITE }, // 32-bit A1 10203040 // mov eax, dword ptr [0x40302010]
{ X86_MOV32ao64, X86_REG_EAX, CS_AC_WRITE }, // 64-bit A1 1020304050607080 // movabs eax, dword ptr [0x8070605040302010]
{ X86_MOV64ao32, X86_REG_RAX, CS_AC_WRITE }, // 64-bit 48 8B04 10203040 // mov rax, qword ptr [0x40302010]
{ X86_MOV64ao64, X86_REG_RAX, CS_AC_WRITE }, // 64-bit 48 A1 1020304050607080 // movabs rax, qword ptr [0x8070605040302010]
{ X86_LODSQ, X86_REG_RAX, CS_AC_WRITE },
{ X86_OR32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SUB32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_TEST32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_ADD32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_XCHG64ar, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_LODSB, X86_REG_AL, CS_AC_WRITE },
{ X86_AND32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_IN16ri, X86_REG_AX, CS_AC_WRITE },
{ X86_CMP64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_XOR32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_XCHG16ar, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_LODSW, X86_REG_AX, CS_AC_WRITE },
{ X86_AND16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_ADC16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_XCHG32ar64, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_ADC8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_CMP32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_AND8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_SCASW, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_XOR8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_SUB16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_OR16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_XCHG32ar, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SBB8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_SCASQ, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SBB32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_XOR64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SUB64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_ADD64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_OR8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_TEST64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SBB16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_TEST8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_IN8ri, X86_REG_AL, CS_AC_WRITE },
{ X86_TEST16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_SCASL, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SUB8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_ADD8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_OR64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_SCASB, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_SBB64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_ADD16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_XOR16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_AND64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_LODSL, X86_REG_EAX, CS_AC_WRITE },
{ X86_CMP8i8, X86_REG_AL, CS_AC_WRITE | CS_AC_READ },
{ X86_ADC64i32, X86_REG_RAX, CS_AC_WRITE | CS_AC_READ },
{ X86_CMP16i16, X86_REG_AX, CS_AC_WRITE | CS_AC_READ },
{ X86_ADC32i32, X86_REG_EAX, CS_AC_WRITE | CS_AC_READ },
{ X86_IN32ri, X86_REG_EAX, CS_AC_WRITE },
{ X86_PUSHCS32, X86_REG_CS, CS_AC_READ },
{ X86_PUSHDS32, X86_REG_DS, CS_AC_READ },
{ X86_PUSHES32, X86_REG_ES, CS_AC_READ },
{ X86_PUSHFS32, X86_REG_FS, CS_AC_READ },
{ X86_PUSHGS32, X86_REG_GS, CS_AC_READ },
{ X86_PUSHSS32, X86_REG_SS, CS_AC_READ },
{ X86_PUSHFS64, X86_REG_FS, CS_AC_READ },
{ X86_PUSHGS64, X86_REG_GS, CS_AC_READ },
{ X86_PUSHCS16, X86_REG_CS, CS_AC_READ },
{ X86_PUSHDS16, X86_REG_DS, CS_AC_READ },
{ X86_PUSHES16, X86_REG_ES, CS_AC_READ },
{ X86_PUSHFS16, X86_REG_FS, CS_AC_READ },
{ X86_PUSHGS16, X86_REG_GS, CS_AC_READ },
{ X86_PUSHSS16, X86_REG_SS, CS_AC_READ },
{ X86_POPDS32, X86_REG_DS, CS_AC_WRITE },
{ X86_POPES32, X86_REG_ES, CS_AC_WRITE },
{ X86_POPFS32, X86_REG_FS, CS_AC_WRITE },
{ X86_POPGS32, X86_REG_GS, CS_AC_WRITE },
{ X86_POPSS32, X86_REG_SS, CS_AC_WRITE },
{ X86_POPFS64, X86_REG_FS, CS_AC_WRITE },
{ X86_POPGS64, X86_REG_GS, CS_AC_WRITE },
{ X86_POPDS16, X86_REG_DS, CS_AC_WRITE },
{ X86_POPES16, X86_REG_ES, CS_AC_WRITE },
{ X86_POPFS16, X86_REG_FS, CS_AC_WRITE },
{ X86_POPGS16, X86_REG_GS, CS_AC_WRITE },
{ X86_POPSS16, X86_REG_SS, CS_AC_WRITE },
#ifndef CAPSTONE_X86_REDUCE
{ X86_SKINIT, X86_REG_EAX, CS_AC_WRITE },
{ X86_VMRUN32, X86_REG_EAX, CS_AC_WRITE },
{ X86_VMRUN64, X86_REG_RAX, CS_AC_WRITE },
{ X86_VMLOAD32, X86_REG_EAX, CS_AC_WRITE },
{ X86_VMLOAD64, X86_REG_RAX, CS_AC_WRITE },
{ X86_VMSAVE32, X86_REG_EAX, CS_AC_READ },
{ X86_VMSAVE64, X86_REG_RAX, CS_AC_READ },
{ X86_FNSTSW16r, X86_REG_AX, CS_AC_WRITE },
{ X86_CMOVB_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVBE_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVE_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVP_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVNB_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVNBE_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVNE_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_CMOVNP_F, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FXCHST0r, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FXCHST0r_alt, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FCOMST0r, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FCOMPST0r, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FCOMPST0r_alt, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FPST0r, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FPST0r_alt, X86_REG_ST0, CS_AC_WRITE },
{ X86_ST_FPNCEST0r, X86_REG_ST0, CS_AC_WRITE },
#endif
};
static struct insn_reg2 insn_regs_intel2[] = {
{ X86_IN8rr, X86_REG_AL, X86_REG_DX, CS_AC_WRITE, CS_AC_READ },
{ X86_IN16rr, X86_REG_AX, X86_REG_DX, CS_AC_WRITE, CS_AC_READ },
{ X86_IN32rr, X86_REG_EAX, X86_REG_DX, CS_AC_WRITE, CS_AC_READ },
{ X86_OUT8rr, X86_REG_DX, X86_REG_AL, CS_AC_READ, CS_AC_READ },
{ X86_OUT16rr, X86_REG_DX, X86_REG_AX, CS_AC_READ, CS_AC_READ },
{ X86_OUT32rr, X86_REG_DX, X86_REG_EAX, CS_AC_READ, CS_AC_READ },
{ X86_INVLPGA32, X86_REG_EAX, X86_REG_ECX, CS_AC_READ, CS_AC_READ },
{ X86_INVLPGA64, X86_REG_RAX, X86_REG_ECX, CS_AC_READ, CS_AC_READ },
};
static struct insn_reg insn_regs_intel_sorted [ARR_SIZE(insn_regs_intel)];
static int regs_cmp(const void *a, const void *b)
{
uint16_t l = ((struct insn_reg *)a)->insn;
uint16_t r = ((struct insn_reg *)b)->insn;
return (l - r);
}
static bool intel_regs_sorted = false;
// return register of given instruction id
// return 0 if not found
// this is to handle instructions embedding accumulate registers into AsmStrs[]
x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid = ARR_SIZE(insn_regs_intel) / 2;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
while (first <= last) {
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
mid = (first + last) / 2;
}
// not found
return 0;
}
bool X86_insn_reg_intel2(unsigned int id, x86_reg *reg1, enum cs_ac_type *access1, x86_reg *reg2, enum cs_ac_type *access2)
{
unsigned int i;
for (i = 0; i < ARR_SIZE(insn_regs_intel2); i++) {
if (insn_regs_intel2[i].insn == id) {
*reg1 = insn_regs_intel2[i].reg1;
*reg2 = insn_regs_intel2[i].reg2;
if (access1)
*access1 = insn_regs_intel2[i].access1;
if (access2)
*access2 = insn_regs_intel2[i].access2;
return true;
}
}
// not found
return false;
}
// ATT just reuses Intel data, but with the order of registers reversed
bool X86_insn_reg_att2(unsigned int id, x86_reg *reg1, enum cs_ac_type *access1, x86_reg *reg2, enum cs_ac_type *access2)
{
unsigned int i;
for (i = 0; i < ARR_SIZE(insn_regs_intel2); i++) {
if (insn_regs_intel2[i].insn == id) {
// reverse order of Intel syntax registers
*reg1 = insn_regs_intel2[i].reg2;
*reg2 = insn_regs_intel2[i].reg1;
if (access1)
*access1 = insn_regs_intel2[i].access2;
if (access2)
*access2 = insn_regs_intel2[i].access1;
return true;
}
}
// not found
return false;
}
x86_reg X86_insn_reg_att(unsigned int id, enum cs_ac_type *access)
{
unsigned int i;
for (i = 0; i < ARR_SIZE(insn_regs_att); i++) {
if (insn_regs_att[i].insn == id) {
if (access)
*access = insn_regs_intel[i].access;
return insn_regs_att[i].reg;
}
}
// not found
return 0;
}
// given MCInst's id, find out if this insn is valid for REPNE prefix
static bool valid_repne(cs_struct *h, unsigned int opcode)
{
unsigned int id;
int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache);
if (i != 0) {
id = insns[i].mapid;
switch(id) {
default:
return false;
case X86_INS_CMPSB:
case X86_INS_CMPSW:
case X86_INS_CMPSQ:
case X86_INS_SCASB:
case X86_INS_SCASW:
case X86_INS_SCASQ:
case X86_INS_MOVSB:
case X86_INS_MOVSW:
case X86_INS_MOVSD:
case X86_INS_MOVSQ:
case X86_INS_LODSB:
case X86_INS_LODSW:
case X86_INS_LODSD:
case X86_INS_LODSQ:
case X86_INS_STOSB:
case X86_INS_STOSW:
case X86_INS_STOSD:
case X86_INS_STOSQ:
case X86_INS_INSB:
case X86_INS_INSW:
case X86_INS_INSD:
case X86_INS_OUTSB:
case X86_INS_OUTSW:
case X86_INS_OUTSD:
return true;
case X86_INS_CMPSD:
if (opcode == X86_CMPSL) // REP CMPSD
return true;
return false;
case X86_INS_SCASD:
if (opcode == X86_SCASL) // REP SCASD
return true;
return false;
}
}
// not found
return false;
}
// given MCInst's id, find out if this insn is valid for REP prefix
static bool valid_rep(cs_struct *h, unsigned int opcode)
{
unsigned int id;
int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache);
if (i != 0) {
id = insns[i].mapid;
switch(id) {
default:
return false;
case X86_INS_MOVSB:
case X86_INS_MOVSW:
case X86_INS_MOVSQ:
case X86_INS_LODSB:
case X86_INS_LODSW:
case X86_INS_LODSQ:
case X86_INS_STOSB:
case X86_INS_STOSW:
case X86_INS_STOSQ:
case X86_INS_INSB:
case X86_INS_INSW:
case X86_INS_INSD:
case X86_INS_OUTSB:
case X86_INS_OUTSW:
case X86_INS_OUTSD:
return true;
// following are some confused instructions, which have the same
// mnemonics in 128bit media instructions. Intel is horribly crazy!
case X86_INS_MOVSD:
if (opcode == X86_MOVSL) // REP MOVSD
return true;
return false;
case X86_INS_LODSD:
if (opcode == X86_LODSL) // REP LODSD
return true;
return false;
case X86_INS_STOSD:
if (opcode == X86_STOSL) // REP STOSD
return true;
return false;
}
}
// not found
return false;
}
// given MCInst's id, find out if this insn is valid for REPE prefix
static bool valid_repe(cs_struct *h, unsigned int opcode)
{
unsigned int id;
int i = insn_find(insns, ARR_SIZE(insns), opcode, &h->insn_cache);
if (i != 0) {
id = insns[i].mapid;
switch(id) {
default:
return false;
case X86_INS_CMPSB:
case X86_INS_CMPSW:
case X86_INS_CMPSQ:
case X86_INS_SCASB:
case X86_INS_SCASW:
case X86_INS_SCASQ:
return true;
// following are some confused instructions, which have the same
// mnemonics in 128bit media instructions. Intel is horribly crazy!
case X86_INS_CMPSD:
if (opcode == X86_CMPSL) // REP CMPSD
return true;
return false;
case X86_INS_SCASD:
if (opcode == X86_SCASL) // REP SCASD
return true;
return false;
}
}
// not found
return false;
}
#ifndef CAPSTONE_DIET
// add *CX register to regs_read[] & regs_write[]
static void add_cx(MCInst *MI)
{
if (MI->csh->detail) {
x86_reg cx;
if (MI->csh->mode & CS_MODE_16)
cx = X86_REG_CX;
else if (MI->csh->mode & CS_MODE_32)
cx = X86_REG_ECX;
else // 64-bit
cx = X86_REG_RCX;
MI->flat_insn->detail->regs_read[MI->flat_insn->detail->regs_read_count] = cx;
MI->flat_insn->detail->regs_read_count++;
MI->flat_insn->detail->regs_write[MI->flat_insn->detail->regs_write_count] = cx;
MI->flat_insn->detail->regs_write_count++;
}
}
#endif
// return true if we patch the mnemonic
bool X86_lockrep(MCInst *MI, SStream *O)
{
unsigned int opcode;
bool res = false;
switch(MI->x86_prefix[0]) {
default:
break;
case 0xf0:
#ifndef CAPSTONE_DIET
SStream_concat(O, "lock|");
#endif
break;
case 0xf2: // repne
opcode = MCInst_getOpcode(MI);
#ifndef CAPSTONE_DIET // only care about memonic in standard (non-diet) mode
if (valid_repne(MI->csh, opcode)) {
SStream_concat(O, "repne|");
add_cx(MI);
} else {
// invalid prefix
MI->x86_prefix[0] = 0;
// handle special cases
#ifndef CAPSTONE_X86_REDUCE
if (opcode == X86_MULPDrr) {
MCInst_setOpcode(MI, X86_MULSDrr);
SStream_concat(O, "mulsd\t");
res = true;
}
#endif
}
#else // diet mode -> only patch opcode in special cases
if (!valid_repne(MI->csh, opcode)) {
MI->x86_prefix[0] = 0;
}
#ifndef CAPSTONE_X86_REDUCE
// handle special cases
if (opcode == X86_MULPDrr) {
MCInst_setOpcode(MI, X86_MULSDrr);
}
#endif
#endif
break;
case 0xf3:
opcode = MCInst_getOpcode(MI);
#ifndef CAPSTONE_DIET // only care about memonic in standard (non-diet) mode
if (valid_rep(MI->csh, opcode)) {
SStream_concat(O, "rep|");
add_cx(MI);
} else if (valid_repe(MI->csh, opcode)) {
SStream_concat(O, "repe|");
add_cx(MI);
} else {
// invalid prefix
MI->x86_prefix[0] = 0;
// handle special cases
#ifndef CAPSTONE_X86_REDUCE
if (opcode == X86_MULPDrr) {
MCInst_setOpcode(MI, X86_MULSSrr);
SStream_concat(O, "mulss\t");
res = true;
}
#endif
}
#else // diet mode -> only patch opcode in special cases
if (!valid_rep(MI->csh, opcode) && !valid_repe(MI->csh, opcode)) {
MI->x86_prefix[0] = 0;
}
#ifndef CAPSTONE_X86_REDUCE
// handle special cases
if (opcode == X86_MULPDrr) {
MCInst_setOpcode(MI, X86_MULSSrr);
}
#endif
#endif
break;
}
// copy normalized prefix[] back to x86.prefix[]
if (MI->csh->detail)
memcpy(MI->flat_insn->detail->x86.prefix, MI->x86_prefix, ARR_SIZE(MI->x86_prefix));
return res;
}
void op_addReg(MCInst *MI, int reg)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].type = X86_OP_REG;
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].reg = reg;
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].size = MI->csh->regsize_map[reg];
MI->flat_insn->detail->x86.op_count++;
}
if (MI->op1_size == 0)
MI->op1_size = MI->csh->regsize_map[reg];
}
void op_addImm(MCInst *MI, int v)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].type = X86_OP_IMM;
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].imm = v;
// if op_count > 0, then this operand's size is taken from the destination op
if (MI->csh->syntax != CS_OPT_SYNTAX_ATT) {
if (MI->flat_insn->detail->x86.op_count > 0)
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].size = MI->flat_insn->detail->x86.operands[0].size;
else
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count].size = MI->imm_size;
} else
MI->has_imm = true;
MI->flat_insn->detail->x86.op_count++;
}
if (MI->op1_size == 0)
MI->op1_size = MI->imm_size;
}
void op_addXopCC(MCInst *MI, int v)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.xop_cc = v;
}
}
void op_addSseCC(MCInst *MI, int v)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.sse_cc = v;
}
}
void op_addAvxCC(MCInst *MI, int v)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.avx_cc = v;
}
}
void op_addAvxRoundingMode(MCInst *MI, int v)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.avx_rm = v;
}
}
// below functions supply details to X86GenAsmWriter*.inc
void op_addAvxZeroOpmask(MCInst *MI)
{
if (MI->csh->detail) {
// link with the previous operand
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count - 1].avx_zero_opmask = true;
}
}
void op_addAvxSae(MCInst *MI)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.avx_sae = true;
}
}
void op_addAvxBroadcast(MCInst *MI, x86_avx_bcast v)
{
if (MI->csh->detail) {
// link with the previous operand
MI->flat_insn->detail->x86.operands[MI->flat_insn->detail->x86.op_count - 1].avx_bcast = v;
}
}
#ifndef CAPSTONE_DIET
// map instruction to its characteristics
typedef struct insn_op {
uint64_t eflags; // how this instruction update EFLAGS
uint8_t access[6];
} insn_op;
static insn_op insn_ops[] = {
{ /* NULL item */
0,
{ 0 }
},
#ifdef CAPSTONE_X86_REDUCE
#include "X86MappingInsnOp_reduce.inc"
#else
#include "X86MappingInsnOp.inc"
#endif
};
// given internal insn id, return operand access info
uint8_t *X86_get_op_access(cs_struct *h, unsigned int id, uint64_t *eflags)
{
int i = insn_find(insns, ARR_SIZE(insns), id, &h->insn_cache);
if (i != 0) {
*eflags = insn_ops[i].eflags;
return insn_ops[i].access;
}
return NULL;
}
void X86_reg_access(const cs_insn *insn,
cs_regs regs_read, uint8_t *regs_read_count,
cs_regs regs_write, uint8_t *regs_write_count)
{
uint8_t i;
uint8_t read_count, write_count;
cs_x86 *x86 = &(insn->detail->x86);
read_count = insn->detail->regs_read_count;
write_count = insn->detail->regs_write_count;
// implicit registers
memcpy(regs_read, insn->detail->regs_read, read_count * sizeof(insn->detail->regs_read[0]));
memcpy(regs_write, insn->detail->regs_write, write_count * sizeof(insn->detail->regs_write[0]));
// explicit registers
for (i = 0; i < x86->op_count; i++) {
cs_x86_op *op = &(x86->operands[i]);
switch((int)op->type) {
case X86_OP_REG:
if ((op->access & CS_AC_READ) && !arr_exist(regs_read, read_count, op->reg)) {
regs_read[read_count] = op->reg;
read_count++;
}
if ((op->access & CS_AC_WRITE) && !arr_exist(regs_write, write_count, op->reg)) {
regs_write[write_count] = op->reg;
write_count++;
}
break;
case X86_OP_MEM:
// registers appeared in memory references always being read
if ((op->mem.segment != X86_REG_INVALID)) {
regs_read[read_count] = op->mem.segment;
read_count++;
}
if ((op->mem.base != X86_REG_INVALID) && !arr_exist(regs_read, read_count, op->mem.base)) {
regs_read[read_count] = op->mem.base;
read_count++;
}
if ((op->mem.index != X86_REG_INVALID) && !arr_exist(regs_read, read_count, op->mem.index)) {
regs_read[read_count] = op->mem.index;
read_count++;
}
default:
break;
}
}
*regs_read_count = read_count;
*regs_write_count = write_count;
}
#endif
// map immediate size to instruction id
static struct size_id {
unsigned char size;
unsigned short id;
} x86_imm_size[] = {
#include "X86ImmSize.inc"
};
// given the instruction name, return the size of its immediate operand (or 0)
int X86_immediate_size(unsigned int id)
{
#if 0
// linear searching
unsigned int i;
for (i = 0; i < ARR_SIZE(x86_imm_size); i++) {
if (id == x86_imm_size[i].id) {
return x86_imm_size[i].size;
}
}
#endif
// binary searching since the IDs is sorted in order
unsigned int left, right, m;
left = 0;
right = ARR_SIZE(x86_imm_size) - 1;
while(left <= right) {
m = (left + right) / 2;
if (id == x86_imm_size[m].id)
return x86_imm_size[m].size;
if (id < x86_imm_size[m].id)
right = m - 1;
else
left = m + 1;
}
// not found
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5271_0 |
crossvul-cpp_data_good_141_0 | /* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */
#if 0
http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf
https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set
#endif
#include <string.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
static RDESContext desctx;
typedef struct _cpu_const_tag {
const char *const key;
ut8 type;
ut32 value;
ut8 size;
} CPU_CONST;
#define CPU_CONST_NONE 0
#define CPU_CONST_PARAM 1
#define CPU_CONST_REG 2
typedef struct _cpu_model_tag {
const char *const model;
int pc;
char *inherit;
struct _cpu_model_tag *inherit_cpu_p;
CPU_CONST *consts[10];
} CPU_MODEL;
typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu);
typedef struct _opcodes_tag_ {
const char *const name;
int mask;
int selector;
inst_handler_t handler;
int cycles;
int size;
ut64 type;
} OPCODE_DESC;
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu);
#define CPU_MODEL_DECL(model, pc, consts) \
{ \
model, \
pc, \
consts \
}
#define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits))))
#define CPU_PC_MASK(cpu) MASK((cpu)->pc)
#define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0))
#define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu)
#define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T }
#define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK }
#define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu)
#define INST_INVALID { *fail = 1; return; }
#define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } }
#define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__)
#define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s))
// Following IO definitions are valid for:
// ATmega8
// ATmega88
CPU_CONST cpu_reg_common[] = {
{ "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) },
{ "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) },
{ "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) },
{ "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_common[] = {
{ "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = {
{ "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_xmega128a4u[] = {
{ "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_pagesize_5_bits[] = {
{ "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_pagesize_7_bits[] = {
{ "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_MODEL cpu_models[] = {
{ .model = "ATmega640", .pc = 15,
.consts = {
cpu_reg_common,
cpu_memsize_m640_m1280m_m1281_m2560_m2561,
cpu_pagesize_7_bits,
NULL
},
},
{
.model = "ATxmega128a4u", .pc = 17,
.consts = {
cpu_reg_common,
cpu_memsize_xmega128a4u,
cpu_pagesize_7_bits,
NULL
}
},
{ .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" },
{ .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" },
{ .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" },
{ .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" },
{ .model = "ATmega88", .pc = 8, .inherit = "ATmega8" },
// CPU_MODEL_DECL ("ATmega168", 13, 512, 512),
// last model is the default AVR - ATmega8 forever!
{
.model = "ATmega8", .pc = 13,
.consts = {
cpu_reg_common,
cpu_memsize_common,
cpu_pagesize_5_bits,
NULL
}
},
};
static CPU_MODEL *get_cpu_model(char *model);
static CPU_MODEL *__get_cpu_model_recursive(char *model) {
CPU_MODEL *cpu = NULL;
for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) {
if (!strcasecmp (model, cpu->model)) {
break;
}
}
// fix inheritance tree
if (cpu->inherit && !cpu->inherit_cpu_p) {
cpu->inherit_cpu_p = get_cpu_model (cpu->inherit);
if (!cpu->inherit_cpu_p) {
eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit);
}
}
return cpu;
}
static CPU_MODEL *get_cpu_model(char *model) {
static CPU_MODEL *cpu = NULL;
// cached value?
if (cpu && !strcasecmp (model, cpu->model))
return cpu;
// do the real search
cpu = __get_cpu_model_recursive (model);
return cpu;
}
static ut32 const_get_value(CPU_CONST *c) {
return c ? MASK (c->size * 8) & c->value : 0;
}
static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) {
CPU_CONST **clist, *citem;
for (clist = cpu->consts; *clist; clist++) {
for (citem = *clist; citem->key; citem++) {
if (!strcmp (c, citem->key)
&& (type == CPU_CONST_NONE || type == citem->type)) {
return citem;
}
}
}
if (cpu->inherit_cpu_p)
return const_by_name (cpu->inherit_cpu_p, type, c);
eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c);
return NULL;
}
static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) {
char *t = r_anal_esil_pop (esil);
if (!t || !r_anal_esil_get_parm (esil, t, v)) {
free (t);
return false;
}
free (t);
return true;
}
static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) {
CPU_CONST **clist, *citem;
for (clist = cpu->consts; *clist; clist++) {
for (citem = *clist; citem && citem->key; citem++) {
if (citem->value == (MASK (citem->size * 8) & v)
&& (type == CPU_CONST_NONE || type == citem->type)) {
return citem;
}
}
}
if (cpu->inherit_cpu_p)
return const_by_value (cpu->inherit_cpu_p, type, v);
return NULL;
}
static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) {
RStrBuf *r = r_strbuf_new ("");
CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port);
if (c != NULL) {
r_strbuf_set (r, c->key);
if (write) {
r_strbuf_append (r, ",=");
}
} else {
r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : "");
}
return r;
}
static void __generic_bitop_flags(RAnalOp *op) {
ESIL_A ("0,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
}
static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) {
if (ireg) {
// preincrement index register
if (prepostdec < 0) {
ESIL_A ("1,%c,-,%c,=,", ireg, ireg);
}
// set register index address
ESIL_A ("%c,", ireg);
// add offset
if (offset != 0) {
ESIL_A ("%d,+,", offset);
}
} else {
ESIL_A ("%d,", offset);
}
if (use_ramp) {
ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd');
}
// set SRAM base address
ESIL_A ("_%s,+,", mem);
// read/write from SRAM
ESIL_A ("%s[1],", st ? "=" : "");
// postincrement index register
if (ireg && prepostdec > 0) {
ESIL_A ("1,%c,+,%c,=,", ireg, ireg);
}
}
static void __generic_pop(RAnalOp *op, int sz) {
if (sz > 1) {
ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1)
ESIL_A ("[%d],", sz); // read value
ESIL_A ("%d,sp,+=,", sz); // sp += item_size
} else {
ESIL_A ("1,sp,+=," // increment stack pointer
"sp,_ram,+,[1],"); // load SRAM[sp]
}
}
static void __generic_push(RAnalOp *op, int sz) {
ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp)
if (sz > 1) {
ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz'
}
ESIL_A ("=[%d],", sz); // store value in stack
ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer
}
static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) {
RStrBuf *d_strbuf, *rk_strbuf;
char *d, *rk;
d_strbuf = r_strbuf_new (NULL);
rk_strbuf = r_strbuf_new (NULL);
r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d);
r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk);
d = r_strbuf_get(d_strbuf);
rk = r_strbuf_get(rk_strbuf);
ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&,"
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&,"
"|,|,hf,=,",
d, rk, rk, d);
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V
"" "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!," "%s,0x80,&,!," "&,"
"" "0,RPICK,0x80,&,!,!," "&,"
"|,vf,=,",
d, rk, d, rk);
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&,"
"|,|,cf,=,",
d, rk, rk, d);
ESIL_A ("vf,nf,^,sf,=,"); // S
r_strbuf_free (d_strbuf);
r_strbuf_free (rk_strbuf);
}
static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) {
__generic_add_update_flags(op, 'r', d, 'r', r);
}
static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) {
RStrBuf *d_strbuf, *rk_strbuf;
char *d, *rk;
d_strbuf = r_strbuf_new (NULL);
rk_strbuf = r_strbuf_new (NULL);
r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d);
r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk);
d = r_strbuf_get(d_strbuf);
rk = r_strbuf_get(rk_strbuf);
ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&,"
"%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&,"
"|,|,hf,=,",
d, rk, rk, d);
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V
"" "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!," "%s,0x80,&,!,!," "&,"
"" "0,RPICK,0x80,&,!,!," "&,"
"|,vf,=,",
d, rk, d, rk);
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
if (carry)
ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z
else
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&,"
"%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&,"
"|,|,cf,=,",
d, rk, rk, d);
ESIL_A ("vf,nf,^,sf,=,"); // S
r_strbuf_free (d_strbuf);
r_strbuf_free (rk_strbuf);
}
static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) {
__generic_sub_update_flags(op, 'r', d, 'r', r, carry);
}
static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) {
__generic_sub_update_flags(op, 'r', d, 'k', k, carry);
}
INST_HANDLER (adc) { // ADC Rd, Rr
// ROL Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C
__generic_add_update_flags_rr(op, d, r); // FLAGS
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (add) { // ADD Rd, Rr
// LSL Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr
__generic_add_update_flags_rr(op, d, r); // FLAGS
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr
// FLAGS:
ESIL_A ("r%d,0x80,&,!," // V
"0,RPICK,0x8000,&,!,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!,!," // C
"0,RPICK,0x8000,&,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
INST_HANDLER (and) { // AND Rd, Rr
// TST Rd
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (andi) { // ANDI Rd, K
// CBR Rd, K (= ANDI Rd, 1-K)
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f);
op->val = k;
ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (asr) { // ASR Rd
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7
ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("nf,vf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = R
}
INST_HANDLER (bclr) { // BCLR s
// CLC
// CLH
// CLI
// CLN
// CLR
// CLS
// CLT
// CLV
// CLZ
int s = (buf[0] >> 4) & 0x7;
ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s);
}
INST_HANDLER (bld) { // BLD Rd, b
if (len < 2) {
return;
}
int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf);
int b = buf[0] & 0x7;
ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0
ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b
}
INST_HANDLER (brbx) { // BRBC s, k
// BRBS s, k
// BRBC/S 0: BRCC BRCS
// BRSH BRLO
// BRBC/S 1: BREQ BRNE
// BRBC/S 2: BRPL BRMI
// BRBC/S 3: BRVC BRVS
// BRBC/S 4: BRGE BRLT
// BRBC/S 5: BRHC BRHS
// BRBC/S 6: BRTC BRTS
// BRBC/S 7: BRID BRIE
int s = buf[0] & 0x7;
op->jump = op->addr
+ ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2))
| (buf[1] & 0x2 ? ~((int) 0x7f) : 0))
+ 2;
op->fail = op->addr + op->size;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to true, this instruction
// needs 2 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s)
ESIL_A (buf[1] & 0x4
? "!," // BRBC => branch if cleared
: "!,!,"); // BRBS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (break) { // BREAK
ESIL_A ("BREAK");
}
INST_HANDLER (bset) { // BSET s
// SEC
// SEH
// SEI
// SEN
// SER
// SES
// SET
// SEV
// SEZ
int s = (buf[0] >> 4) & 0x7;
ESIL_A ("%d,1,<<,sreg,|=,", s);
}
INST_HANDLER (bst) { // BST Rd, b
if (len < 2) {
return;
}
ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b
((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r
buf[0] & 0x7); // b
}
INST_HANDLER (call) { // CALL k
if (len < 4) {
return;
}
op->jump = (buf[2] << 1)
| (buf[3] << 9)
| (buf[1] & 0x01) << 23
| (buf[0] & 0x01) << 17
| (buf[0] & 0xf0) << 14;
op->fail = op->addr + op->size;
op->cycles = cpu->pc <= 16 ? 3 : 4;
if (!STR_BEGINS (cpu->model, "ATxmega")) {
op->cycles--; // AT*mega optimizes one cycle
}
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
}
INST_HANDLER (cbi) { // CBI A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RStrBuf *io_port;
op->family = R_ANAL_OP_FAMILY_IO;
op->type2 = 1;
op->val = a;
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port);
r_strbuf_free (io_port);
// write result to port a
io_port = __generic_io_dest (a, 1, cpu);
ESIL_A ("%s,", r_strbuf_get (io_port));
r_strbuf_free (io_port);
}
INST_HANDLER (com) { // COM Rd
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4);
ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd
// FLAGS:
ESIL_A ("0,cf,=,"); // C
__generic_bitop_flags (op); // ...rest...
}
INST_HANDLER (cp) { // CP Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10);
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr
__generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry)
}
INST_HANDLER (cpc) { // CPC Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10);
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C
__generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry)
}
INST_HANDLER (cpi) { // CPI Rd, K
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4);
ESIL_A ("%d,r%d,-,", k, d); // Rd - k
__generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry)
}
INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to true, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (dec) { // DEC Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("-1,r%d,+,", d); // --Rd
// FLAGS:
ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (des) { // DES k
if (desctx.round < 16) { //DES
op->type = R_ANAL_OP_TYPE_CRYPTO;
op->cycles = 1; //redo this
r_strbuf_setf (&op->esil, "%d,des", desctx.round);
}
}
INST_HANDLER (eijmp) { // EIJMP
ut64 z, eind;
// read z and eind for calculating jump address on runtime
r_anal_esil_reg_read (anal->esil, "z", &z, NULL);
r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL);
// real target address may change during execution, so this value will
// be changing all the time
op->jump = ((eind << 16) + z) << 1;
// jump
ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,");
// cycles
op->cycles = 2;
}
INST_HANDLER (eicall) { // EICALL
// push pc in stack
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
// do a standard EIJMP
INST_CALL (eijmp);
// fix cycles
op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4;
}
INST_HANDLER (elpm) { // ELPM
// ELPM Rd
// ELPM Rd, Z+
int d = ((buf[1] & 0xfe) == 0x90)
? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd
: 0; // R0
ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z
ESIL_A ("r%d,=,", d); // Rd = [1]
if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) {
ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z)
}
}
INST_HANDLER (eor) { // EOR Rd, Rr
// CLR Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (fmul) { // FMUL Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (fmuls) { // FMULS Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,");
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr
ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (fmulsu) { // FMULSU Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,");
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("r%d", r); // unsigned Rr
ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (ijmp) { // IJMP k
ut64 z;
// read z for calculating jump address on runtime
r_anal_esil_reg_read (anal->esil, "z", &z, NULL);
// real target address may change during execution, so this value will
// be changing all the time
op->jump = z << 1;
op->cycles = 2;
ESIL_A ("1,z,<<,pc,=,"); // jump!
}
INST_HANDLER (icall) { // ICALL k
// push pc in stack
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
// do a standard IJMP
INST_CALL (ijmp);
// fix cycles
if (!STR_BEGINS (cpu->model, "ATxmega")) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (in) { // IN Rd, A
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4);
int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3);
RStrBuf *io_src = __generic_io_dest (a, 0, cpu);
op->type2 = 0;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r);
r_strbuf_free (io_src);
}
INST_HANDLER (inc) { // INC Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("1,r%d,+,", d); // ++Rd
// FLAGS:
ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (jmp) { // JMP k
op->jump = (buf[2] << 1)
| (buf[3] << 9)
| (buf[1] & 0x01) << 23
| (buf[0] & 0x01) << 17
| (buf[0] & 0xf0) << 14;
op->cycles = 3;
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
}
INST_HANDLER (lac) { // LAC Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (las) { // LAS Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,|,", d); // 0: (Z) | Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (lat) { // LAT Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (ld) { // LD Rd, X
// LD Rd, X+
// LD Rd, -X
// read memory
__generic_ld_st (
op, "ram",
'x', // use index register X
0, // no use RAMP* registers
(buf[0] & 0xf) == 0xe
? -1 // pre decremented
: (buf[0] & 0xf) == 0xd
? 1 // post incremented
: 0, // no increment
0, // offset always 0
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// cycles
op->cycles = (buf[0] & 0x3) == 0
? 2 // LD Rd, X
: (buf[0] & 0x3) == 1
? 2 // LD Rd, X+
: 3; // LD Rd, -X
if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z
// LD Rd, Y+ LD Rd, Z+
// LD Rd, -Y LD Rd, -Z
// LD Rd, Y+q LD Rd, Z+q
// calculate offset (this value only has sense in some opcodes,
// but we are optimistic and we calculate it always)
int offset = (buf[1] & 0x20)
| ((buf[1] & 0xc) << 1)
| (buf[0] & 0x7);
// read memory
__generic_ld_st (
op, "ram",
buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z
0, // no use RAMP* registers
!(buf[1] & 0x10)
? 0 // no increment
: buf[0] & 0x1
? 1 // post incremented
: -1, // pre decremented
!(buf[1] & 0x10) ? offset : 0, // offset or not offset
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// cycles
op->cycles =
(buf[1] & 0x10) == 0
? (!offset ? 1 : 3) // LDD
: (buf[0] & 0x3) == 0
? 1 // LD Rd, X
: (buf[0] & 0x3) == 1
? 2 // LD Rd, X+
: 3; // LD Rd, -X
if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (ldi) { // LDI Rd, K
int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4);
int d = ((buf[0] >> 4) & 0xf) + 16;
op->val = k;
ESIL_A ("0x%x,r%d,=,", k, d);
}
INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
// load value from RAMPD:k
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
#if 0
INST_HANDLER (lds16) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0x0f)
| ((buf[1] << 3) & 0x30)
| ((buf[1] << 4) & 0x40)
| (~(buf[1] << 4) & 0x80);
op->ptr = k;
// load value from @k
__generic_ld_st (op, "ram", 0, 0, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
#endif
INST_HANDLER (lpm) { // LPM
// LPM Rd, Z
// LPM Rd, Z+
ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]);
// read program memory
__generic_ld_st (
op, "prog",
'z', // index register Y/Z
1, // use RAMP* registers
(ins & 0xfe0f) == 0x9005
? 1 // post incremented
: 0, // no increment
0, // not offset
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,",
(ins == 0x95c8)
? 0 // LPM (r0)
: ((buf[0] >> 4) & 0xf) // LPM Rd
| ((buf[1] & 0x1) << 4));
}
INST_HANDLER (lsr) { // LSR Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1)
ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("nf,vf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = R
}
INST_HANDLER (mov) { // MOV Rd, Rr
int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f);
int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f);
ESIL_A ("r%d,r%d,=,", r, d);
}
INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr
int d = (buf[0] & 0xf0) >> 3;
int r = (buf[0] & 0x0f) << 1;
ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1);
}
INST_HANDLER (mul) { // MUL Rd, Rr
int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f);
int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f);
ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (muls) { // MULS Rd, Rr
int d = (buf[0] >> 4 & 0x0f) + 16;
int r = (buf[0] & 0x0f) + 16;
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("*,"); // 0: (Rd*Rr)
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (mulsu) { // MULSU Rd, Rr
int d = (buf[0] >> 4 & 0x07) + 16;
int r = (buf[0] & 0x07) + 16;
ESIL_A ("r%d,", r); // unsigned Rr
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("*,"); // 0: (Rd*Rr)
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (neg) { // NEG Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd)
ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H
ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V
ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N
ESIL_A ("DUP,!,zf,=,"); // Z
ESIL_A ("DUP,!,!,cf,=,"); // C
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (nop) { // NOP
ESIL_A (",,");
}
INST_HANDLER (or) { // OR Rd, Rr
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr)
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,vf,=,"); // V
ESIL_A ("nf,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (ori) { // ORI Rd, K
// SBR Rd, K
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4);
op->val = k;
ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k)
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,vf,=,"); // V
ESIL_A ("nf,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (out) { // OUT A, Rr
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4);
int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3);
RStrBuf *io_dst = __generic_io_dest (a, 1, cpu);
op->type2 = 1;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst));
r_strbuf_free (io_dst);
}
INST_HANDLER (pop) { // POP Rd
int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
__generic_pop (op, 1);
ESIL_A ("r%d,=,", d); // store in Rd
}
INST_HANDLER (push) { // PUSH Rr
int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
ESIL_A ("r%d,", r); // load Rr
__generic_push (op, 1); // push it into stack
// cycles
op->cycles = !STR_BEGINS (cpu->model, "ATxmega")
? 1 // AT*mega optimizes one cycle
: 2;
}
INST_HANDLER (rcall) { // RCALL k
// target address
op->jump = (op->addr
+ (((((buf[1] & 0xf) << 8) | buf[0]) << 1)
| (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0)))
+ 2) & CPU_PC_MASK (cpu);
op->fail = op->addr + op->size;
// esil
ESIL_A ("pc,"); // esil already points to next
// instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
// cycles
if (!strncasecmp (cpu->model, "ATtiny", 6)) {
op->cycles = 4; // ATtiny is always slow
} else {
// PC size decides required runtime!
op->cycles = cpu->pc <= 16 ? 3 : 4;
if (!STR_BEGINS (cpu->model, "ATxmega")) {
op->cycles--; // ATxmega optimizes one cycle
}
}
}
INST_HANDLER (ret) { // RET
op->eob = true;
// esil
__generic_pop (op, CPU_PC_SIZE (cpu));
ESIL_A ("pc,=,"); // jump!
// cycles
if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit
op->cycles++; // (i.e. a 22-bit bus), add one extra cycle
}
}
INST_HANDLER (reti) { // RETI
//XXX: There are not privileged instructions in ATMEL/AVR
op->family = R_ANAL_OP_FAMILY_PRIV;
// first perform a standard 'ret'
INST_CALL (ret);
// RETI: The I-bit is cleared by hardware after an interrupt
// has occurred, and is set by the RETI instruction to enable
// subsequent interrupts
ESIL_A ("1,if,=,");
}
INST_HANDLER (rjmp) { // RJMP k
op->jump = (op->addr
#ifdef _MSC_VER
#pragma message ("anal_avr.c: WARNING: Probably broken on windows")
+ ((((( buf[1] & 0xf) << 9) | (buf[0] << 1)))
| (buf[1] & 0x8 ? ~(0x1fff) : 0))
#else
+ ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1)))
| (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0))
#endif
+ 2) & CPU_PC_MASK (cpu);
ESIL_A ("%"PFMT64d",pc,=,", op->jump);
}
INST_HANDLER (ror) { // ROR Rd
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7)
ESIL_A ("r%d,1,&,cf,=,", d); // C
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (sbc) { // SBC Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C)
__generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sbci) { // SBCI Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf);
op->val = k;
ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C)
__generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sub) { // SUB Rd, Rr
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k)
__generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (subi) { // SUBI Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf);
op->val = k;
ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k)
__generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sbi) { // SBI A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RStrBuf *io_port;
op->type2 = 1;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port);
r_strbuf_free (io_port);
// write result to port a
io_port = __generic_io_dest (a, 1, cpu);
ESIL_A ("%s,", r_strbuf_get (io_port));
r_strbuf_free (io_port);
}
INST_HANDLER (sbix) { // SBIC A, b
// SBIS A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RAnalOp next_op;
RStrBuf *io_port;
op->type2 = 0;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size,
len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBIC => branch if 0
: "!,!,"); // SBIS => branch if 1
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
r_strbuf_free (io_port);
}
INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr)
ESIL_A ("r%d,0x80,&,!,!," // V
"0,RPICK,0x8000,&,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!," // C
"0,RPICK,0x8000,&,!,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
INST_HANDLER (sbrx) { // SBRC Rr, b
// SBRS Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op = {0};
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (sleep) { // SLEEP
ESIL_A ("BREAK");
}
INST_HANDLER (spm) { // SPM Z+
ut64 spmcsr;
// read SPM Control Register (SPMCR)
r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL);
// clear SPMCSR
ESIL_A ("0x7c,spmcsr,&=,");
// decide action depending on the old value of SPMCSR
switch (spmcsr & 0x7f) {
case 0x03: // PAGE ERASE
// invoke SPM_CLEAR_PAGE (erases target page writing
// the 0xff value
ESIL_A ("16,rampz,<<,z,+,"); // push target address
ESIL_A ("SPM_PAGE_ERASE,"); // do magic
break;
case 0x01: // FILL TEMPORARY BUFFER
ESIL_A ("r1,r0,"); // push data
ESIL_A ("z,"); // push target address
ESIL_A ("SPM_PAGE_FILL,"); // do magic
break;
case 0x05: // WRITE PAGE
ESIL_A ("16,rampz,<<,z,+,"); // push target address
ESIL_A ("SPM_PAGE_WRITE,"); // do magic
break;
default:
eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n",
(unsigned int) spmcsr);
}
op->cycles = 1; // This is truly false. Datasheets do not publish how
// many cycles this instruction uses in all its
// operation modes and I am pretty sure that this value
// can vary substantially from one MCU type to another.
// So... one cycle is fine.
}
INST_HANDLER (st) { // ST X, Rr
// ST X+, Rr
// ST -X, Rr
// load register
ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// write in memory
__generic_ld_st (
op, "ram",
'x', // use index register X
0, // no use RAMP* registers
(buf[0] & 0xf) == 0xe
? -1 // pre decremented
: (buf[0] & 0xf) == 0xd
? 1 // post increment
: 0, // no increment
0, // offset always 0
1); // store operation (st)
// // cycles
// op->cycles = buf[0] & 0x3 == 0
// ? 2 // LD Rd, X
// : buf[0] & 0x3 == 1
// ? 2 // LD Rd, X+
// : 3; // LD Rd, -X
// if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// // AT*mega optimizes 1 cycle!
// op->cycles--;
// }
}
INST_HANDLER (std) { // ST Y, Rr ST Z, Rr
// ST Y+, Rr ST Z+, Rr
// ST -Y, Rr ST -Z, Rr
// ST Y+q, Rr ST Z+q, Rr
// load register
ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// write in memory
__generic_ld_st (
op, "ram",
buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z
0, // no use RAMP* registers
!(buf[1] & 0x10)
? 0 // no increment
: buf[0] & 0x1
? 1 // post incremented
: -1, // pre decremented
!(buf[1] & 0x10)
? (buf[1] & 0x20) // offset
| ((buf[1] & 0xc) << 1)
| (buf[0] & 0x7)
: 0, // no offset
1); // load operation (!st)
// // cycles
// op->cycles =
// buf[1] & 0x1 == 0
// ? !(offset ? 1 : 3) // LDD
// : buf[0] & 0x3 == 0
// ? 1 // LD Rd, X
// : buf[0] & 0x3 == 1
// ? 2 // LD Rd, X+
// : 3; // LD Rd, -X
// if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// // AT*mega optimizes 1 cycle!
// op->cycles--;
// }
}
INST_HANDLER (swap) { // SWAP Rd
int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf
ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf
ESIL_A ("|,", d); // S[0] | S[1]
ESIL_A ("r%d,=,", d); // Rd = result
}
OPCODE_DESC opcodes[] = {
// op mask select cycles size type
INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK
INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL
INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP
INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL
INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP
INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM
INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP
INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET
INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI
INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP
INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ...
INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s
INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s
INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr
INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr
INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr
INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k
INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K
INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K
INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K
INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K
INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr
INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd
INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b
INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd
INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z
INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+
INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd
INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd
INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd
INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd
INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X
INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+
INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X
INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k
INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr
INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z
INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+
INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd
INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd
INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd
INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr
INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd
INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr
INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr
INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr
INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd
INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k
INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k
INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b
INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b
INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b
INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b
INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b
INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b
INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+
INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z
INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr
INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr
INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr
INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr
INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr
INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k
INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k
INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr
INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr
INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr
INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr
INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr
INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr
INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr
INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr
INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A
//INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k
INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr
INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K
INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K
INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K
INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K
INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k
INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k
INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr
INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr
INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q
INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr
INST_LAST
};
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
if (len < 2) {
return NULL;
}
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
// initialize op struct
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
// process opcode
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
// copy default cycles/size values
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
// op->fail = addr + op->size;
op->addr = addr;
// start void esil expression
r_strbuf_setf (&op->esil, "");
// handle opcode
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
// eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr);
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
// remove trailing coma (COMETE LA COMA)
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
// ignore reserved opcodes (if they have not been caught by the previous loop)
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
// An unknown or invalid option has appeared.
// -- Throw pokeball!
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
// launch esil trap (for communicating upper layers about this weird
// and stinky situation
r_strbuf_set (&op->esil, "1,$");
return NULL;
}
static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) {
CPU_MODEL *cpu;
ut64 offset;
// init op
if (!op) {
return 2;
}
// select cpu info
cpu = get_cpu_model (anal->cpu);
// set memory layout registers
if (anal->esil) {
offset = 0;
r_anal_esil_reg_write (anal->esil, "_prog", offset);
offset += (1 << cpu->pc);
r_anal_esil_reg_write (anal->esil, "_io", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start"));
r_anal_esil_reg_write (anal->esil, "_sram", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size"));
r_anal_esil_reg_write (anal->esil, "_eeprom", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size"));
r_anal_esil_reg_write (anal->esil, "_page", offset);
}
// process opcode
avr_op_analyze (anal, op, addr, buf, len, cpu);
return op->size;
}
static int avr_custom_des (RAnalEsil *esil) {
ut64 key, encrypt, text,des_round;
ut32 key_lo, key_hi, buf_lo, buf_hi;
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
if (!__esil_pop_argument (esil, &des_round)) {
return false;
}
r_anal_esil_reg_read (esil, "hf", &encrypt, NULL);
r_anal_esil_reg_read (esil, "deskey", &key, NULL);
r_anal_esil_reg_read (esil, "text", &text, NULL);
key_lo = key & UT32_MAX;
key_hi = key >> 32;
buf_lo = text & UT32_MAX;
buf_hi = text >> 32;
if (des_round != desctx.round) {
desctx.round = des_round;
}
if (!desctx.round) {
int i;
//generating all round keys
r_des_permute_key (&key_lo, &key_hi);
for (i = 0; i < 16; i++) {
r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi);
}
r_des_permute_block0 (&buf_lo, &buf_hi);
}
if (encrypt) {
r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]);
} else {
r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]);
}
if (desctx.round == 15) {
r_des_permute_block1 (&buf_hi, &buf_lo);
desctx.round = 0;
} else {
desctx.round++;
}
r_anal_esil_reg_write (esil, "text", text);
return true;
}
// ESIL operation SPM_PAGE_ERASE
static int avr_custom_spm_page_erase(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut8 c;
ut64 addr, page_size_bits, i;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
// get details about current MCU and fix input address
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
// align base address to page_size_bits
addr &= ~(MASK (page_size_bits));
// perform erase
//eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr);
c = 0xff;
for (i = 0; i < (1ULL << page_size_bits); i++) {
r_anal_esil_mem_write (
esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1);
}
return true;
}
// ESIL operation SPM_PAGE_FILL
static int avr_custom_spm_page_fill(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut64 addr, page_size_bits, i;
ut8 r0, r1;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address, r0, r1
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r0 = i;
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r1 = i;
// get details about current MCU and fix input address
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
// align and crop base address
addr &= (MASK (page_size_bits) ^ 1);
// perform write to temporary page
//eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr);
r_anal_esil_mem_write (esil, addr++, &r0, 1);
r_anal_esil_mem_write (esil, addr++, &r1, 1);
return true;
}
// ESIL operation SPM_PAGE_WRITE
static int avr_custom_spm_page_write(RAnalEsil *esil) {
CPU_MODEL *cpu;
char *t = NULL;
ut64 addr, page_size_bits, tmp_page;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address
if (!__esil_pop_argument (esil, &addr)) {
return false;
}
// get details about current MCU and fix input address and base address
// of the internal temporary page
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL);
// align base address to page_size_bits
addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu));
// perform writing
//eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr);
if (!(t = malloc (1 << page_size_bits))) {
eprintf ("Cannot alloc a buffer for copying the temporary page.\n");
return false;
}
r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits);
r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits);
return true;
}
static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) {
CPU_MODEL *cpu;
if (!esil || !esil->anal) {
return 0;
}
// select cpu info
cpu = get_cpu_model (esil->anal->cpu);
// crop registers and force certain values
if (!strcmp (name, "pc")) {
*val &= CPU_PC_MASK (cpu);
} else if (!strcmp (name, "pcl")) {
if (cpu->pc < 8) {
*val &= MASK (8);
}
} else if (!strcmp (name, "pch")) {
*val = cpu->pc > 8
? *val & MASK (cpu->pc - 8)
: 0;
}
return 0;
}
static int esil_avr_init(RAnalEsil *esil) {
if (!esil) {
return false;
}
desctx.round = 0;
r_anal_esil_set_op (esil, "des", avr_custom_des);
r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase);
r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill);
r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write);
esil->cb.hook_reg_write = esil_avr_hook_reg_write;
return true;
}
static int esil_avr_fini(RAnalEsil *esil) {
return true;
}
static int set_reg_profile(RAnal *anal) {
const char *p =
"=PC pcl\n"
"=SP sp\n"
// explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html
// and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file
"=A0 r25\n"
"=A1 r24\n"
"=A2 r23\n"
"=A3 r22\n"
"=R0 r24\n"
#if 0
PC: 16- or 22-bit program counter
SP: 8- or 16-bit stack pointer
SREG: 8-bit status register
RAMPX, RAMPY, RAMPZ, RAMPD and EIND:
#endif
// 8bit registers x 32
"gpr r0 .8 0 0\n"
"gpr r1 .8 1 0\n"
"gpr r2 .8 2 0\n"
"gpr r3 .8 3 0\n"
"gpr r4 .8 4 0\n"
"gpr r5 .8 5 0\n"
"gpr r6 .8 6 0\n"
"gpr r7 .8 7 0\n"
"gpr text .64 0 0\n"
"gpr r8 .8 8 0\n"
"gpr r9 .8 9 0\n"
"gpr r10 .8 10 0\n"
"gpr r11 .8 11 0\n"
"gpr r12 .8 12 0\n"
"gpr r13 .8 13 0\n"
"gpr r14 .8 14 0\n"
"gpr r15 .8 15 0\n"
"gpr deskey .64 8 0\n"
"gpr r16 .8 16 0\n"
"gpr r17 .8 17 0\n"
"gpr r18 .8 18 0\n"
"gpr r19 .8 19 0\n"
"gpr r20 .8 20 0\n"
"gpr r21 .8 21 0\n"
"gpr r22 .8 22 0\n"
"gpr r23 .8 23 0\n"
"gpr r24 .8 24 0\n"
"gpr r25 .8 25 0\n"
"gpr r26 .8 26 0\n"
"gpr r27 .8 27 0\n"
"gpr r28 .8 28 0\n"
"gpr r29 .8 29 0\n"
"gpr r30 .8 30 0\n"
"gpr r31 .8 31 0\n"
// 16 bit overlapped registers for 16 bit math
"gpr r17:r16 .16 16 0\n"
"gpr r19:r18 .16 18 0\n"
"gpr r21:r20 .16 20 0\n"
"gpr r23:r22 .16 22 0\n"
"gpr r25:r24 .16 24 0\n"
"gpr r27:r26 .16 26 0\n"
"gpr r29:r28 .16 28 0\n"
"gpr r31:r30 .16 30 0\n"
// 16 bit overlapped registers for memory addressing
"gpr x .16 26 0\n"
"gpr y .16 28 0\n"
"gpr z .16 30 0\n"
// program counter
// NOTE: program counter size in AVR depends on the CPU model. It seems that
// the PC may range from 16 bits to 22 bits.
"gpr pc .32 32 0\n"
"gpr pcl .16 32 0\n"
"gpr pch .16 34 0\n"
// special purpose registers
"gpr sp .16 36 0\n"
"gpr spl .8 36 0\n"
"gpr sph .8 37 0\n"
// status bit register (SREG)
"gpr sreg .8 38 0\n"
"gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts.
"gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero.
"gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result.
"gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow.
"gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison.
"gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic.
"gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit.
"gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled.
// 8bit segment registers to be added to X, Y, Z to get 24bit offsets
"gpr rampx .8 39 0\n"
"gpr rampy .8 40 0\n"
"gpr rampz .8 41 0\n"
"gpr rampd .8 42 0\n"
"gpr eind .8 43 0\n"
// memory mapping emulator registers
// _prog
// the program flash. It has its own address space.
// _ram
// _io
// start of the data addres space. It is the same address of IO,
// because IO is the first memory space addressable in the AVR.
// _sram
// start of the SRAM (this offset depends on IO size, and it is
// inside the _ram address space)
// _eeprom
// this is another address space, outside ram and flash
// _page
// this is the temporary page used by the SPM instruction. This
// memory is not directly addressable and it is used internally by
// the CPU when autoflashing.
"gpr _prog .32 44 0\n"
"gpr _page .32 48 0\n"
"gpr _eeprom .32 52 0\n"
"gpr _ram .32 56 0\n"
"gpr _io .32 56 0\n"
"gpr _sram .32 60 0\n"
// other important MCU registers
// spmcsr/spmcr
// Store Program Memory Control and Status Register (SPMCSR)
"gpr spmcsr .8 64 0\n"
;
return r_reg_set_profile_string (anal->reg, p);
}
static int archinfo(RAnal *anal, int q) {
if (q == R_ANAL_ARCHINFO_ALIGN)
return 2;
if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE)
return 4;
if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE)
return 2;
return 2; // XXX
}
static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) {
RAnalOp *op = NULL;
ut8 *ret = NULL;
int idx;
if (!(op = r_anal_op_new ())) {
return NULL;
}
if (!(ret = malloc (size))) {
r_anal_op_free (op);
return NULL;
}
memset (ret, 0xff, size);
CPU_MODEL *cpu = get_cpu_model (anal->cpu);
for (idx = 0; idx + 1 < size; idx += op->size) {
OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu);
if (op->size < 1) {
break;
}
if (!opcode_desc) { // invalid instruction
continue;
}
// the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching
// (things like memory offsets or jump addresses)
if (op->size == 4) {
ret[idx + 2] = 0;
ret[idx + 3] = 0;
}
if (op->ptr != UT64_MAX || op->jump != UT64_MAX) {
ret[idx] = opcode_desc->mask;
ret[idx + 1] = opcode_desc->mask >> 8;
}
}
r_anal_op_free (op);
return ret;
}
RAnalPlugin r_anal_plugin_avr = {
.name = "avr",
.desc = "AVR code analysis plugin",
.license = "LGPL3",
.arch = "avr",
.esil = true,
.archinfo = archinfo,
.bits = 8 | 16, // 24 big regs conflicts
.op = &avr_op,
.set_reg_profile = &set_reg_profile,
.esil_init = esil_avr_init,
.esil_fini = esil_avr_fini,
.anal_mask = anal_mask_avr,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
.data = &r_anal_plugin_avr,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_141_0 |
crossvul-cpp_data_bad_376_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_msgs.h"
#include "memdebug.h" /* keep this as LAST include */
#define WARN_PREFIX "Warning: "
#define NOTE_PREFIX "Note: "
static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
}
/*
* Emit 'note' formatted message on configured 'errors' stream, if verbose was
* selected.
*/
void notef(struct GlobalConfig *config, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if(config->tracetype)
voutf(config, NOTE_PREFIX, fmt, ap);
va_end(ap);
}
/*
* Emit warning formatted message on configured 'errors' stream unless
* mute (--silent) was selected.
*/
void warnf(struct GlobalConfig *config, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
voutf(config, WARN_PREFIX, fmt, ap);
va_end(ap);
}
/*
* Emit help formatted message on given stream.
*/
void helpf(FILE *errors, const char *fmt, ...)
{
if(fmt) {
va_list ap;
va_start(ap, fmt);
fputs("curl: ", errors); /* prefix it */
vfprintf(errors, fmt, ap);
va_end(ap);
}
fprintf(errors, "curl: try 'curl --help' "
#ifdef USE_MANUAL
"or 'curl --manual' "
#endif
"for more information\n");
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_376_0 |
crossvul-cpp_data_good_5297_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR L EEEEE %
% R R L E %
% RRRR L EEE %
% R R L E %
% R R LLLLL EEEEE %
% %
% %
% Read URT RLE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-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/pixel.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s R L E %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsRLE() returns MagickTrue if the image format type, identified by the
% magick string, is RLE.
%
% The format of the ReadRLEImage method is:
%
% MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\122\314",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
% image file and returns it. It allocates the memory necessary for the new
% Image structure and returns a pointer to the new image.
%
% The format of the ReadRLEImage method is:
%
% Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
%
*/
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == 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)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 64)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate RLE pixels.
*/
if (image->alpha_trait != UndefinedPixelTrait)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*number_planes_filled;
pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->alpha_trait == UndefinedPixelTrait)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType)
ScaleCharToQuantum(*p);
image->colormap[i].green=(MagickRealType)
ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=(MagickRealType)
ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->alpha_trait == UndefinedPixelTrait)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
index].red),q);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
index].green),q);
if (IsValidColormapIndex(image,(ssize_t) *p++,&index,
exception) == MagickFalse)
break;
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
index].blue),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,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 ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterRLEImage() adds attributes for the RLE image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterRLEImage method is:
%
% size_t RegisterRLEImage(void)
%
*/
ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("RLE","RLE","Utah Run length encoded image");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r R L E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterRLEImage() removes format registrations made by the
% RLE module from the list of supported formats.
%
% The format of the UnregisterRLEImage method is:
%
% UnregisterRLEImage(void)
%
*/
ModuleExport void UnregisterRLEImage(void)
{
(void) UnregisterMagickInfo("RLE");
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5297_0 |
crossvul-cpp_data_bad_2911_1 | /*
* USB Attached SCSI
* Note that this is not the same as the USB Mass Storage driver
*
* Copyright Hans de Goede <hdegoede@redhat.com> for Red Hat, Inc. 2013 - 2016
* Copyright Matthew Wilcox for Intel Corp, 2010
* Copyright Sarah Sharp for Intel Corp, 2010
*
* Distributed under the terms of the GNU GPL, version two.
*/
#include <linux/blkdev.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb_usual.h>
#include <linux/usb/hcd.h>
#include <linux/usb/storage.h>
#include <linux/usb/uas.h>
#include <scsi/scsi.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include "uas-detect.h"
#include "scsiglue.h"
#define MAX_CMNDS 256
struct uas_dev_info {
struct usb_interface *intf;
struct usb_device *udev;
struct usb_anchor cmd_urbs;
struct usb_anchor sense_urbs;
struct usb_anchor data_urbs;
unsigned long flags;
int qdepth, resetting;
unsigned cmd_pipe, status_pipe, data_in_pipe, data_out_pipe;
unsigned use_streams:1;
unsigned shutdown:1;
struct scsi_cmnd *cmnd[MAX_CMNDS];
spinlock_t lock;
struct work_struct work;
};
enum {
SUBMIT_STATUS_URB = BIT(1),
ALLOC_DATA_IN_URB = BIT(2),
SUBMIT_DATA_IN_URB = BIT(3),
ALLOC_DATA_OUT_URB = BIT(4),
SUBMIT_DATA_OUT_URB = BIT(5),
ALLOC_CMD_URB = BIT(6),
SUBMIT_CMD_URB = BIT(7),
COMMAND_INFLIGHT = BIT(8),
DATA_IN_URB_INFLIGHT = BIT(9),
DATA_OUT_URB_INFLIGHT = BIT(10),
COMMAND_ABORTED = BIT(11),
IS_IN_WORK_LIST = BIT(12),
};
/* Overrides scsi_pointer */
struct uas_cmd_info {
unsigned int state;
unsigned int uas_tag;
struct urb *cmd_urb;
struct urb *data_in_urb;
struct urb *data_out_urb;
};
/* I hate forward declarations, but I actually have a loop */
static int uas_submit_urbs(struct scsi_cmnd *cmnd,
struct uas_dev_info *devinfo);
static void uas_do_work(struct work_struct *work);
static int uas_try_complete(struct scsi_cmnd *cmnd, const char *caller);
static void uas_free_streams(struct uas_dev_info *devinfo);
static void uas_log_cmd_state(struct scsi_cmnd *cmnd, const char *prefix,
int status);
static void uas_do_work(struct work_struct *work)
{
struct uas_dev_info *devinfo =
container_of(work, struct uas_dev_info, work);
struct uas_cmd_info *cmdinfo;
struct scsi_cmnd *cmnd;
unsigned long flags;
int i, err;
spin_lock_irqsave(&devinfo->lock, flags);
if (devinfo->resetting)
goto out;
for (i = 0; i < devinfo->qdepth; i++) {
if (!devinfo->cmnd[i])
continue;
cmnd = devinfo->cmnd[i];
cmdinfo = (void *)&cmnd->SCp;
if (!(cmdinfo->state & IS_IN_WORK_LIST))
continue;
err = uas_submit_urbs(cmnd, cmnd->device->hostdata);
if (!err)
cmdinfo->state &= ~IS_IN_WORK_LIST;
else
schedule_work(&devinfo->work);
}
out:
spin_unlock_irqrestore(&devinfo->lock, flags);
}
static void uas_add_work(struct uas_cmd_info *cmdinfo)
{
struct scsi_pointer *scp = (void *)cmdinfo;
struct scsi_cmnd *cmnd = container_of(scp, struct scsi_cmnd, SCp);
struct uas_dev_info *devinfo = cmnd->device->hostdata;
lockdep_assert_held(&devinfo->lock);
cmdinfo->state |= IS_IN_WORK_LIST;
schedule_work(&devinfo->work);
}
static void uas_zap_pending(struct uas_dev_info *devinfo, int result)
{
struct uas_cmd_info *cmdinfo;
struct scsi_cmnd *cmnd;
unsigned long flags;
int i, err;
spin_lock_irqsave(&devinfo->lock, flags);
for (i = 0; i < devinfo->qdepth; i++) {
if (!devinfo->cmnd[i])
continue;
cmnd = devinfo->cmnd[i];
cmdinfo = (void *)&cmnd->SCp;
uas_log_cmd_state(cmnd, __func__, 0);
/* Sense urbs were killed, clear COMMAND_INFLIGHT manually */
cmdinfo->state &= ~COMMAND_INFLIGHT;
cmnd->result = result << 16;
err = uas_try_complete(cmnd, __func__);
WARN_ON(err != 0);
}
spin_unlock_irqrestore(&devinfo->lock, flags);
}
static void uas_sense(struct urb *urb, struct scsi_cmnd *cmnd)
{
struct sense_iu *sense_iu = urb->transfer_buffer;
struct scsi_device *sdev = cmnd->device;
if (urb->actual_length > 16) {
unsigned len = be16_to_cpup(&sense_iu->len);
if (len + 16 != urb->actual_length) {
int newlen = min(len + 16, urb->actual_length) - 16;
if (newlen < 0)
newlen = 0;
sdev_printk(KERN_INFO, sdev, "%s: urb length %d "
"disagrees with IU sense data length %d, "
"using %d bytes of sense data\n", __func__,
urb->actual_length, len, newlen);
len = newlen;
}
memcpy(cmnd->sense_buffer, sense_iu->sense, len);
}
cmnd->result = sense_iu->status;
}
static void uas_log_cmd_state(struct scsi_cmnd *cmnd, const char *prefix,
int status)
{
struct uas_cmd_info *ci = (void *)&cmnd->SCp;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
scmd_printk(KERN_INFO, cmnd,
"%s %d uas-tag %d inflight:%s%s%s%s%s%s%s%s%s%s%s%s ",
prefix, status, cmdinfo->uas_tag,
(ci->state & SUBMIT_STATUS_URB) ? " s-st" : "",
(ci->state & ALLOC_DATA_IN_URB) ? " a-in" : "",
(ci->state & SUBMIT_DATA_IN_URB) ? " s-in" : "",
(ci->state & ALLOC_DATA_OUT_URB) ? " a-out" : "",
(ci->state & SUBMIT_DATA_OUT_URB) ? " s-out" : "",
(ci->state & ALLOC_CMD_URB) ? " a-cmd" : "",
(ci->state & SUBMIT_CMD_URB) ? " s-cmd" : "",
(ci->state & COMMAND_INFLIGHT) ? " CMD" : "",
(ci->state & DATA_IN_URB_INFLIGHT) ? " IN" : "",
(ci->state & DATA_OUT_URB_INFLIGHT) ? " OUT" : "",
(ci->state & COMMAND_ABORTED) ? " abort" : "",
(ci->state & IS_IN_WORK_LIST) ? " work" : "");
scsi_print_command(cmnd);
}
static void uas_free_unsubmitted_urbs(struct scsi_cmnd *cmnd)
{
struct uas_cmd_info *cmdinfo;
if (!cmnd)
return;
cmdinfo = (void *)&cmnd->SCp;
if (cmdinfo->state & SUBMIT_CMD_URB)
usb_free_urb(cmdinfo->cmd_urb);
/* data urbs may have never gotten their submit flag set */
if (!(cmdinfo->state & DATA_IN_URB_INFLIGHT))
usb_free_urb(cmdinfo->data_in_urb);
if (!(cmdinfo->state & DATA_OUT_URB_INFLIGHT))
usb_free_urb(cmdinfo->data_out_urb);
}
static int uas_try_complete(struct scsi_cmnd *cmnd, const char *caller)
{
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct uas_dev_info *devinfo = (void *)cmnd->device->hostdata;
lockdep_assert_held(&devinfo->lock);
if (cmdinfo->state & (COMMAND_INFLIGHT |
DATA_IN_URB_INFLIGHT |
DATA_OUT_URB_INFLIGHT |
COMMAND_ABORTED))
return -EBUSY;
devinfo->cmnd[cmdinfo->uas_tag - 1] = NULL;
uas_free_unsubmitted_urbs(cmnd);
cmnd->scsi_done(cmnd);
return 0;
}
static void uas_xfer_data(struct urb *urb, struct scsi_cmnd *cmnd,
unsigned direction)
{
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
int err;
cmdinfo->state |= direction | SUBMIT_STATUS_URB;
err = uas_submit_urbs(cmnd, cmnd->device->hostdata);
if (err) {
uas_add_work(cmdinfo);
}
}
static bool uas_evaluate_response_iu(struct response_iu *riu, struct scsi_cmnd *cmnd)
{
u8 response_code = riu->response_code;
switch (response_code) {
case RC_INCORRECT_LUN:
cmnd->result = DID_BAD_TARGET << 16;
break;
case RC_TMF_SUCCEEDED:
cmnd->result = DID_OK << 16;
break;
case RC_TMF_NOT_SUPPORTED:
cmnd->result = DID_TARGET_FAILURE << 16;
break;
default:
uas_log_cmd_state(cmnd, "response iu", response_code);
cmnd->result = DID_ERROR << 16;
break;
}
return response_code == RC_TMF_SUCCEEDED;
}
static void uas_stat_cmplt(struct urb *urb)
{
struct iu *iu = urb->transfer_buffer;
struct Scsi_Host *shost = urb->context;
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
struct urb *data_in_urb = NULL;
struct urb *data_out_urb = NULL;
struct scsi_cmnd *cmnd;
struct uas_cmd_info *cmdinfo;
unsigned long flags;
unsigned int idx;
int status = urb->status;
bool success;
spin_lock_irqsave(&devinfo->lock, flags);
if (devinfo->resetting)
goto out;
if (status) {
if (status != -ENOENT && status != -ECONNRESET && status != -ESHUTDOWN)
dev_err(&urb->dev->dev, "stat urb: status %d\n", status);
goto out;
}
idx = be16_to_cpup(&iu->tag) - 1;
if (idx >= MAX_CMNDS || !devinfo->cmnd[idx]) {
dev_err(&urb->dev->dev,
"stat urb: no pending cmd for uas-tag %d\n", idx + 1);
goto out;
}
cmnd = devinfo->cmnd[idx];
cmdinfo = (void *)&cmnd->SCp;
if (!(cmdinfo->state & COMMAND_INFLIGHT)) {
uas_log_cmd_state(cmnd, "unexpected status cmplt", 0);
goto out;
}
switch (iu->iu_id) {
case IU_ID_STATUS:
uas_sense(urb, cmnd);
if (cmnd->result != 0) {
/* cancel data transfers on error */
data_in_urb = usb_get_urb(cmdinfo->data_in_urb);
data_out_urb = usb_get_urb(cmdinfo->data_out_urb);
}
cmdinfo->state &= ~COMMAND_INFLIGHT;
uas_try_complete(cmnd, __func__);
break;
case IU_ID_READ_READY:
if (!cmdinfo->data_in_urb ||
(cmdinfo->state & DATA_IN_URB_INFLIGHT)) {
uas_log_cmd_state(cmnd, "unexpected read rdy", 0);
break;
}
uas_xfer_data(urb, cmnd, SUBMIT_DATA_IN_URB);
break;
case IU_ID_WRITE_READY:
if (!cmdinfo->data_out_urb ||
(cmdinfo->state & DATA_OUT_URB_INFLIGHT)) {
uas_log_cmd_state(cmnd, "unexpected write rdy", 0);
break;
}
uas_xfer_data(urb, cmnd, SUBMIT_DATA_OUT_URB);
break;
case IU_ID_RESPONSE:
cmdinfo->state &= ~COMMAND_INFLIGHT;
success = uas_evaluate_response_iu((struct response_iu *)iu, cmnd);
if (!success) {
/* Error, cancel data transfers */
data_in_urb = usb_get_urb(cmdinfo->data_in_urb);
data_out_urb = usb_get_urb(cmdinfo->data_out_urb);
}
uas_try_complete(cmnd, __func__);
break;
default:
uas_log_cmd_state(cmnd, "bogus IU", iu->iu_id);
}
out:
usb_free_urb(urb);
spin_unlock_irqrestore(&devinfo->lock, flags);
/* Unlinking of data urbs must be done without holding the lock */
if (data_in_urb) {
usb_unlink_urb(data_in_urb);
usb_put_urb(data_in_urb);
}
if (data_out_urb) {
usb_unlink_urb(data_out_urb);
usb_put_urb(data_out_urb);
}
}
static void uas_data_cmplt(struct urb *urb)
{
struct scsi_cmnd *cmnd = urb->context;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct uas_dev_info *devinfo = (void *)cmnd->device->hostdata;
struct scsi_data_buffer *sdb = NULL;
unsigned long flags;
int status = urb->status;
spin_lock_irqsave(&devinfo->lock, flags);
if (cmdinfo->data_in_urb == urb) {
sdb = scsi_in(cmnd);
cmdinfo->state &= ~DATA_IN_URB_INFLIGHT;
cmdinfo->data_in_urb = NULL;
} else if (cmdinfo->data_out_urb == urb) {
sdb = scsi_out(cmnd);
cmdinfo->state &= ~DATA_OUT_URB_INFLIGHT;
cmdinfo->data_out_urb = NULL;
}
if (sdb == NULL) {
WARN_ON_ONCE(1);
goto out;
}
if (devinfo->resetting)
goto out;
/* Data urbs should not complete before the cmd urb is submitted */
if (cmdinfo->state & SUBMIT_CMD_URB) {
uas_log_cmd_state(cmnd, "unexpected data cmplt", 0);
goto out;
}
if (status) {
if (status != -ENOENT && status != -ECONNRESET && status != -ESHUTDOWN)
uas_log_cmd_state(cmnd, "data cmplt err", status);
/* error: no data transfered */
sdb->resid = sdb->length;
} else {
sdb->resid = sdb->length - urb->actual_length;
}
uas_try_complete(cmnd, __func__);
out:
usb_free_urb(urb);
spin_unlock_irqrestore(&devinfo->lock, flags);
}
static void uas_cmd_cmplt(struct urb *urb)
{
if (urb->status)
dev_err(&urb->dev->dev, "cmd cmplt err %d\n", urb->status);
usb_free_urb(urb);
}
static struct urb *uas_alloc_data_urb(struct uas_dev_info *devinfo, gfp_t gfp,
struct scsi_cmnd *cmnd,
enum dma_data_direction dir)
{
struct usb_device *udev = devinfo->udev;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct urb *urb = usb_alloc_urb(0, gfp);
struct scsi_data_buffer *sdb = (dir == DMA_FROM_DEVICE)
? scsi_in(cmnd) : scsi_out(cmnd);
unsigned int pipe = (dir == DMA_FROM_DEVICE)
? devinfo->data_in_pipe : devinfo->data_out_pipe;
if (!urb)
goto out;
usb_fill_bulk_urb(urb, udev, pipe, NULL, sdb->length,
uas_data_cmplt, cmnd);
if (devinfo->use_streams)
urb->stream_id = cmdinfo->uas_tag;
urb->num_sgs = udev->bus->sg_tablesize ? sdb->table.nents : 0;
urb->sg = sdb->table.sgl;
out:
return urb;
}
static struct urb *uas_alloc_sense_urb(struct uas_dev_info *devinfo, gfp_t gfp,
struct scsi_cmnd *cmnd)
{
struct usb_device *udev = devinfo->udev;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct urb *urb = usb_alloc_urb(0, gfp);
struct sense_iu *iu;
if (!urb)
goto out;
iu = kzalloc(sizeof(*iu), gfp);
if (!iu)
goto free;
usb_fill_bulk_urb(urb, udev, devinfo->status_pipe, iu, sizeof(*iu),
uas_stat_cmplt, cmnd->device->host);
if (devinfo->use_streams)
urb->stream_id = cmdinfo->uas_tag;
urb->transfer_flags |= URB_FREE_BUFFER;
out:
return urb;
free:
usb_free_urb(urb);
return NULL;
}
static struct urb *uas_alloc_cmd_urb(struct uas_dev_info *devinfo, gfp_t gfp,
struct scsi_cmnd *cmnd)
{
struct usb_device *udev = devinfo->udev;
struct scsi_device *sdev = cmnd->device;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct urb *urb = usb_alloc_urb(0, gfp);
struct command_iu *iu;
int len;
if (!urb)
goto out;
len = cmnd->cmd_len - 16;
if (len < 0)
len = 0;
len = ALIGN(len, 4);
iu = kzalloc(sizeof(*iu) + len, gfp);
if (!iu)
goto free;
iu->iu_id = IU_ID_COMMAND;
iu->tag = cpu_to_be16(cmdinfo->uas_tag);
iu->prio_attr = UAS_SIMPLE_TAG;
iu->len = len;
int_to_scsilun(sdev->lun, &iu->lun);
memcpy(iu->cdb, cmnd->cmnd, cmnd->cmd_len);
usb_fill_bulk_urb(urb, udev, devinfo->cmd_pipe, iu, sizeof(*iu) + len,
uas_cmd_cmplt, NULL);
urb->transfer_flags |= URB_FREE_BUFFER;
out:
return urb;
free:
usb_free_urb(urb);
return NULL;
}
/*
* Why should I request the Status IU before sending the Command IU? Spec
* says to, but also says the device may receive them in any order. Seems
* daft to me.
*/
static struct urb *uas_submit_sense_urb(struct scsi_cmnd *cmnd, gfp_t gfp)
{
struct uas_dev_info *devinfo = cmnd->device->hostdata;
struct urb *urb;
int err;
urb = uas_alloc_sense_urb(devinfo, gfp, cmnd);
if (!urb)
return NULL;
usb_anchor_urb(urb, &devinfo->sense_urbs);
err = usb_submit_urb(urb, gfp);
if (err) {
usb_unanchor_urb(urb);
uas_log_cmd_state(cmnd, "sense submit err", err);
usb_free_urb(urb);
return NULL;
}
return urb;
}
static int uas_submit_urbs(struct scsi_cmnd *cmnd,
struct uas_dev_info *devinfo)
{
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct urb *urb;
int err;
lockdep_assert_held(&devinfo->lock);
if (cmdinfo->state & SUBMIT_STATUS_URB) {
urb = uas_submit_sense_urb(cmnd, GFP_ATOMIC);
if (!urb)
return SCSI_MLQUEUE_DEVICE_BUSY;
cmdinfo->state &= ~SUBMIT_STATUS_URB;
}
if (cmdinfo->state & ALLOC_DATA_IN_URB) {
cmdinfo->data_in_urb = uas_alloc_data_urb(devinfo, GFP_ATOMIC,
cmnd, DMA_FROM_DEVICE);
if (!cmdinfo->data_in_urb)
return SCSI_MLQUEUE_DEVICE_BUSY;
cmdinfo->state &= ~ALLOC_DATA_IN_URB;
}
if (cmdinfo->state & SUBMIT_DATA_IN_URB) {
usb_anchor_urb(cmdinfo->data_in_urb, &devinfo->data_urbs);
err = usb_submit_urb(cmdinfo->data_in_urb, GFP_ATOMIC);
if (err) {
usb_unanchor_urb(cmdinfo->data_in_urb);
uas_log_cmd_state(cmnd, "data in submit err", err);
return SCSI_MLQUEUE_DEVICE_BUSY;
}
cmdinfo->state &= ~SUBMIT_DATA_IN_URB;
cmdinfo->state |= DATA_IN_URB_INFLIGHT;
}
if (cmdinfo->state & ALLOC_DATA_OUT_URB) {
cmdinfo->data_out_urb = uas_alloc_data_urb(devinfo, GFP_ATOMIC,
cmnd, DMA_TO_DEVICE);
if (!cmdinfo->data_out_urb)
return SCSI_MLQUEUE_DEVICE_BUSY;
cmdinfo->state &= ~ALLOC_DATA_OUT_URB;
}
if (cmdinfo->state & SUBMIT_DATA_OUT_URB) {
usb_anchor_urb(cmdinfo->data_out_urb, &devinfo->data_urbs);
err = usb_submit_urb(cmdinfo->data_out_urb, GFP_ATOMIC);
if (err) {
usb_unanchor_urb(cmdinfo->data_out_urb);
uas_log_cmd_state(cmnd, "data out submit err", err);
return SCSI_MLQUEUE_DEVICE_BUSY;
}
cmdinfo->state &= ~SUBMIT_DATA_OUT_URB;
cmdinfo->state |= DATA_OUT_URB_INFLIGHT;
}
if (cmdinfo->state & ALLOC_CMD_URB) {
cmdinfo->cmd_urb = uas_alloc_cmd_urb(devinfo, GFP_ATOMIC, cmnd);
if (!cmdinfo->cmd_urb)
return SCSI_MLQUEUE_DEVICE_BUSY;
cmdinfo->state &= ~ALLOC_CMD_URB;
}
if (cmdinfo->state & SUBMIT_CMD_URB) {
usb_anchor_urb(cmdinfo->cmd_urb, &devinfo->cmd_urbs);
err = usb_submit_urb(cmdinfo->cmd_urb, GFP_ATOMIC);
if (err) {
usb_unanchor_urb(cmdinfo->cmd_urb);
uas_log_cmd_state(cmnd, "cmd submit err", err);
return SCSI_MLQUEUE_DEVICE_BUSY;
}
cmdinfo->cmd_urb = NULL;
cmdinfo->state &= ~SUBMIT_CMD_URB;
cmdinfo->state |= COMMAND_INFLIGHT;
}
return 0;
}
static int uas_queuecommand_lck(struct scsi_cmnd *cmnd,
void (*done)(struct scsi_cmnd *))
{
struct scsi_device *sdev = cmnd->device;
struct uas_dev_info *devinfo = sdev->hostdata;
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
unsigned long flags;
int idx, err;
BUILD_BUG_ON(sizeof(struct uas_cmd_info) > sizeof(struct scsi_pointer));
/* Re-check scsi_block_requests now that we've the host-lock */
if (cmnd->device->host->host_self_blocked)
return SCSI_MLQUEUE_DEVICE_BUSY;
if ((devinfo->flags & US_FL_NO_ATA_1X) &&
(cmnd->cmnd[0] == ATA_12 || cmnd->cmnd[0] == ATA_16)) {
memcpy(cmnd->sense_buffer, usb_stor_sense_invalidCDB,
sizeof(usb_stor_sense_invalidCDB));
cmnd->result = SAM_STAT_CHECK_CONDITION;
cmnd->scsi_done(cmnd);
return 0;
}
spin_lock_irqsave(&devinfo->lock, flags);
if (devinfo->resetting) {
cmnd->result = DID_ERROR << 16;
cmnd->scsi_done(cmnd);
spin_unlock_irqrestore(&devinfo->lock, flags);
return 0;
}
/* Find a free uas-tag */
for (idx = 0; idx < devinfo->qdepth; idx++) {
if (!devinfo->cmnd[idx])
break;
}
if (idx == devinfo->qdepth) {
spin_unlock_irqrestore(&devinfo->lock, flags);
return SCSI_MLQUEUE_DEVICE_BUSY;
}
cmnd->scsi_done = done;
memset(cmdinfo, 0, sizeof(*cmdinfo));
cmdinfo->uas_tag = idx + 1; /* uas-tag == usb-stream-id, so 1 based */
cmdinfo->state = SUBMIT_STATUS_URB | ALLOC_CMD_URB | SUBMIT_CMD_URB;
switch (cmnd->sc_data_direction) {
case DMA_FROM_DEVICE:
cmdinfo->state |= ALLOC_DATA_IN_URB | SUBMIT_DATA_IN_URB;
break;
case DMA_BIDIRECTIONAL:
cmdinfo->state |= ALLOC_DATA_IN_URB | SUBMIT_DATA_IN_URB;
case DMA_TO_DEVICE:
cmdinfo->state |= ALLOC_DATA_OUT_URB | SUBMIT_DATA_OUT_URB;
case DMA_NONE:
break;
}
if (!devinfo->use_streams)
cmdinfo->state &= ~(SUBMIT_DATA_IN_URB | SUBMIT_DATA_OUT_URB);
err = uas_submit_urbs(cmnd, devinfo);
if (err) {
/* If we did nothing, give up now */
if (cmdinfo->state & SUBMIT_STATUS_URB) {
spin_unlock_irqrestore(&devinfo->lock, flags);
return SCSI_MLQUEUE_DEVICE_BUSY;
}
uas_add_work(cmdinfo);
}
devinfo->cmnd[idx] = cmnd;
spin_unlock_irqrestore(&devinfo->lock, flags);
return 0;
}
static DEF_SCSI_QCMD(uas_queuecommand)
/*
* For now we do not support actually sending an abort to the device, so
* this eh always fails. Still we must define it to make sure that we've
* dropped all references to the cmnd in question once this function exits.
*/
static int uas_eh_abort_handler(struct scsi_cmnd *cmnd)
{
struct uas_cmd_info *cmdinfo = (void *)&cmnd->SCp;
struct uas_dev_info *devinfo = (void *)cmnd->device->hostdata;
struct urb *data_in_urb = NULL;
struct urb *data_out_urb = NULL;
unsigned long flags;
spin_lock_irqsave(&devinfo->lock, flags);
uas_log_cmd_state(cmnd, __func__, 0);
/* Ensure that try_complete does not call scsi_done */
cmdinfo->state |= COMMAND_ABORTED;
/* Drop all refs to this cmnd, kill data urbs to break their ref */
devinfo->cmnd[cmdinfo->uas_tag - 1] = NULL;
if (cmdinfo->state & DATA_IN_URB_INFLIGHT)
data_in_urb = usb_get_urb(cmdinfo->data_in_urb);
if (cmdinfo->state & DATA_OUT_URB_INFLIGHT)
data_out_urb = usb_get_urb(cmdinfo->data_out_urb);
uas_free_unsubmitted_urbs(cmnd);
spin_unlock_irqrestore(&devinfo->lock, flags);
if (data_in_urb) {
usb_kill_urb(data_in_urb);
usb_put_urb(data_in_urb);
}
if (data_out_urb) {
usb_kill_urb(data_out_urb);
usb_put_urb(data_out_urb);
}
return FAILED;
}
static int uas_eh_device_reset_handler(struct scsi_cmnd *cmnd)
{
struct scsi_device *sdev = cmnd->device;
struct uas_dev_info *devinfo = sdev->hostdata;
struct usb_device *udev = devinfo->udev;
unsigned long flags;
int err;
err = usb_lock_device_for_reset(udev, devinfo->intf);
if (err) {
shost_printk(KERN_ERR, sdev->host,
"%s FAILED to get lock err %d\n", __func__, err);
return FAILED;
}
shost_printk(KERN_INFO, sdev->host, "%s start\n", __func__);
spin_lock_irqsave(&devinfo->lock, flags);
devinfo->resetting = 1;
spin_unlock_irqrestore(&devinfo->lock, flags);
usb_kill_anchored_urbs(&devinfo->cmd_urbs);
usb_kill_anchored_urbs(&devinfo->sense_urbs);
usb_kill_anchored_urbs(&devinfo->data_urbs);
uas_zap_pending(devinfo, DID_RESET);
err = usb_reset_device(udev);
spin_lock_irqsave(&devinfo->lock, flags);
devinfo->resetting = 0;
spin_unlock_irqrestore(&devinfo->lock, flags);
usb_unlock_device(udev);
if (err) {
shost_printk(KERN_INFO, sdev->host, "%s FAILED err %d\n",
__func__, err);
return FAILED;
}
shost_printk(KERN_INFO, sdev->host, "%s success\n", __func__);
return SUCCESS;
}
static int uas_target_alloc(struct scsi_target *starget)
{
struct uas_dev_info *devinfo = (struct uas_dev_info *)
dev_to_shost(starget->dev.parent)->hostdata;
if (devinfo->flags & US_FL_NO_REPORT_LUNS)
starget->no_report_luns = 1;
return 0;
}
static int uas_slave_alloc(struct scsi_device *sdev)
{
struct uas_dev_info *devinfo =
(struct uas_dev_info *)sdev->host->hostdata;
sdev->hostdata = devinfo;
/*
* USB has unusual DMA-alignment requirements: Although the
* starting address of each scatter-gather element doesn't matter,
* the length of each element except the last must be divisible
* by the Bulk maxpacket value. There's currently no way to
* express this by block-layer constraints, so we'll cop out
* and simply require addresses to be aligned at 512-byte
* boundaries. This is okay since most block I/O involves
* hardware sectors that are multiples of 512 bytes in length,
* and since host controllers up through USB 2.0 have maxpacket
* values no larger than 512.
*
* But it doesn't suffice for Wireless USB, where Bulk maxpacket
* values can be as large as 2048. To make that work properly
* will require changes to the block layer.
*/
blk_queue_update_dma_alignment(sdev->request_queue, (512 - 1));
if (devinfo->flags & US_FL_MAX_SECTORS_64)
blk_queue_max_hw_sectors(sdev->request_queue, 64);
else if (devinfo->flags & US_FL_MAX_SECTORS_240)
blk_queue_max_hw_sectors(sdev->request_queue, 240);
return 0;
}
static int uas_slave_configure(struct scsi_device *sdev)
{
struct uas_dev_info *devinfo = sdev->hostdata;
if (devinfo->flags & US_FL_NO_REPORT_OPCODES)
sdev->no_report_opcodes = 1;
/* A few buggy USB-ATA bridges don't understand FUA */
if (devinfo->flags & US_FL_BROKEN_FUA)
sdev->broken_fua = 1;
scsi_change_queue_depth(sdev, devinfo->qdepth - 2);
return 0;
}
static struct scsi_host_template uas_host_template = {
.module = THIS_MODULE,
.name = "uas",
.queuecommand = uas_queuecommand,
.target_alloc = uas_target_alloc,
.slave_alloc = uas_slave_alloc,
.slave_configure = uas_slave_configure,
.eh_abort_handler = uas_eh_abort_handler,
.eh_device_reset_handler = uas_eh_device_reset_handler,
.this_id = -1,
.sg_tablesize = SG_NONE,
.skip_settle_delay = 1,
};
#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
vendorName, productName, useProtocol, useTransport, \
initFunction, flags) \
{ USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
.driver_info = (flags) }
static struct usb_device_id uas_usb_ids[] = {
# include "unusual_uas.h"
{ USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, USB_SC_SCSI, USB_PR_BULK) },
{ USB_INTERFACE_INFO(USB_CLASS_MASS_STORAGE, USB_SC_SCSI, USB_PR_UAS) },
{ }
};
MODULE_DEVICE_TABLE(usb, uas_usb_ids);
#undef UNUSUAL_DEV
static int uas_switch_interface(struct usb_device *udev,
struct usb_interface *intf)
{
int alt;
alt = uas_find_uas_alt_setting(intf);
if (alt < 0)
return alt;
return usb_set_interface(udev,
intf->altsetting[0].desc.bInterfaceNumber, alt);
}
static int uas_configure_endpoints(struct uas_dev_info *devinfo)
{
struct usb_host_endpoint *eps[4] = { };
struct usb_device *udev = devinfo->udev;
int r;
r = uas_find_endpoints(devinfo->intf->cur_altsetting, eps);
if (r)
return r;
devinfo->cmd_pipe = usb_sndbulkpipe(udev,
usb_endpoint_num(&eps[0]->desc));
devinfo->status_pipe = usb_rcvbulkpipe(udev,
usb_endpoint_num(&eps[1]->desc));
devinfo->data_in_pipe = usb_rcvbulkpipe(udev,
usb_endpoint_num(&eps[2]->desc));
devinfo->data_out_pipe = usb_sndbulkpipe(udev,
usb_endpoint_num(&eps[3]->desc));
if (udev->speed < USB_SPEED_SUPER) {
devinfo->qdepth = 32;
devinfo->use_streams = 0;
} else {
devinfo->qdepth = usb_alloc_streams(devinfo->intf, eps + 1,
3, MAX_CMNDS, GFP_NOIO);
if (devinfo->qdepth < 0)
return devinfo->qdepth;
devinfo->use_streams = 1;
}
return 0;
}
static void uas_free_streams(struct uas_dev_info *devinfo)
{
struct usb_device *udev = devinfo->udev;
struct usb_host_endpoint *eps[3];
eps[0] = usb_pipe_endpoint(udev, devinfo->status_pipe);
eps[1] = usb_pipe_endpoint(udev, devinfo->data_in_pipe);
eps[2] = usb_pipe_endpoint(udev, devinfo->data_out_pipe);
usb_free_streams(devinfo->intf, eps, 3, GFP_NOIO);
}
static int uas_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
int result = -ENOMEM;
struct Scsi_Host *shost = NULL;
struct uas_dev_info *devinfo;
struct usb_device *udev = interface_to_usbdev(intf);
unsigned long dev_flags;
if (!uas_use_uas_driver(intf, id, &dev_flags))
return -ENODEV;
if (uas_switch_interface(udev, intf))
return -ENODEV;
shost = scsi_host_alloc(&uas_host_template,
sizeof(struct uas_dev_info));
if (!shost)
goto set_alt0;
shost->max_cmd_len = 16 + 252;
shost->max_id = 1;
shost->max_lun = 256;
shost->max_channel = 0;
shost->sg_tablesize = udev->bus->sg_tablesize;
devinfo = (struct uas_dev_info *)shost->hostdata;
devinfo->intf = intf;
devinfo->udev = udev;
devinfo->resetting = 0;
devinfo->shutdown = 0;
devinfo->flags = dev_flags;
init_usb_anchor(&devinfo->cmd_urbs);
init_usb_anchor(&devinfo->sense_urbs);
init_usb_anchor(&devinfo->data_urbs);
spin_lock_init(&devinfo->lock);
INIT_WORK(&devinfo->work, uas_do_work);
result = uas_configure_endpoints(devinfo);
if (result)
goto set_alt0;
/*
* 1 tag is reserved for untagged commands +
* 1 tag to avoid off by one errors in some bridge firmwares
*/
shost->can_queue = devinfo->qdepth - 2;
usb_set_intfdata(intf, shost);
result = scsi_add_host(shost, &intf->dev);
if (result)
goto free_streams;
scsi_scan_host(shost);
return result;
free_streams:
uas_free_streams(devinfo);
usb_set_intfdata(intf, NULL);
set_alt0:
usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, 0);
if (shost)
scsi_host_put(shost);
return result;
}
static int uas_cmnd_list_empty(struct uas_dev_info *devinfo)
{
unsigned long flags;
int i, r = 1;
spin_lock_irqsave(&devinfo->lock, flags);
for (i = 0; i < devinfo->qdepth; i++) {
if (devinfo->cmnd[i]) {
r = 0; /* Not empty */
break;
}
}
spin_unlock_irqrestore(&devinfo->lock, flags);
return r;
}
/*
* Wait for any pending cmnds to complete, on usb-2 sense_urbs may temporarily
* get empty while there still is more work to do due to sense-urbs completing
* with a READ/WRITE_READY iu code, so keep waiting until the list gets empty.
*/
static int uas_wait_for_pending_cmnds(struct uas_dev_info *devinfo)
{
unsigned long start_time;
int r;
start_time = jiffies;
do {
flush_work(&devinfo->work);
r = usb_wait_anchor_empty_timeout(&devinfo->sense_urbs, 5000);
if (r == 0)
return -ETIME;
r = usb_wait_anchor_empty_timeout(&devinfo->data_urbs, 500);
if (r == 0)
return -ETIME;
if (time_after(jiffies, start_time + 5 * HZ))
return -ETIME;
} while (!uas_cmnd_list_empty(devinfo));
return 0;
}
static int uas_pre_reset(struct usb_interface *intf)
{
struct Scsi_Host *shost = usb_get_intfdata(intf);
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
unsigned long flags;
if (devinfo->shutdown)
return 0;
/* Block new requests */
spin_lock_irqsave(shost->host_lock, flags);
scsi_block_requests(shost);
spin_unlock_irqrestore(shost->host_lock, flags);
if (uas_wait_for_pending_cmnds(devinfo) != 0) {
shost_printk(KERN_ERR, shost, "%s: timed out\n", __func__);
scsi_unblock_requests(shost);
return 1;
}
uas_free_streams(devinfo);
return 0;
}
static int uas_post_reset(struct usb_interface *intf)
{
struct Scsi_Host *shost = usb_get_intfdata(intf);
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
unsigned long flags;
int err;
if (devinfo->shutdown)
return 0;
err = uas_configure_endpoints(devinfo);
if (err) {
shost_printk(KERN_ERR, shost,
"%s: alloc streams error %d after reset",
__func__, err);
return 1;
}
spin_lock_irqsave(shost->host_lock, flags);
scsi_report_bus_reset(shost, 0);
spin_unlock_irqrestore(shost->host_lock, flags);
scsi_unblock_requests(shost);
return 0;
}
static int uas_suspend(struct usb_interface *intf, pm_message_t message)
{
struct Scsi_Host *shost = usb_get_intfdata(intf);
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
if (uas_wait_for_pending_cmnds(devinfo) != 0) {
shost_printk(KERN_ERR, shost, "%s: timed out\n", __func__);
return -ETIME;
}
return 0;
}
static int uas_resume(struct usb_interface *intf)
{
return 0;
}
static int uas_reset_resume(struct usb_interface *intf)
{
struct Scsi_Host *shost = usb_get_intfdata(intf);
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
unsigned long flags;
int err;
err = uas_configure_endpoints(devinfo);
if (err) {
shost_printk(KERN_ERR, shost,
"%s: alloc streams error %d after reset",
__func__, err);
return -EIO;
}
spin_lock_irqsave(shost->host_lock, flags);
scsi_report_bus_reset(shost, 0);
spin_unlock_irqrestore(shost->host_lock, flags);
return 0;
}
static void uas_disconnect(struct usb_interface *intf)
{
struct Scsi_Host *shost = usb_get_intfdata(intf);
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
unsigned long flags;
spin_lock_irqsave(&devinfo->lock, flags);
devinfo->resetting = 1;
spin_unlock_irqrestore(&devinfo->lock, flags);
cancel_work_sync(&devinfo->work);
usb_kill_anchored_urbs(&devinfo->cmd_urbs);
usb_kill_anchored_urbs(&devinfo->sense_urbs);
usb_kill_anchored_urbs(&devinfo->data_urbs);
uas_zap_pending(devinfo, DID_NO_CONNECT);
scsi_remove_host(shost);
uas_free_streams(devinfo);
scsi_host_put(shost);
}
/*
* Put the device back in usb-storage mode on shutdown, as some BIOS-es
* hang on reboot when the device is still in uas mode. Note the reset is
* necessary as some devices won't revert to usb-storage mode without it.
*/
static void uas_shutdown(struct device *dev)
{
struct usb_interface *intf = to_usb_interface(dev);
struct usb_device *udev = interface_to_usbdev(intf);
struct Scsi_Host *shost = usb_get_intfdata(intf);
struct uas_dev_info *devinfo = (struct uas_dev_info *)shost->hostdata;
if (system_state != SYSTEM_RESTART)
return;
devinfo->shutdown = 1;
uas_free_streams(devinfo);
usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, 0);
usb_reset_device(udev);
}
static struct usb_driver uas_driver = {
.name = "uas",
.probe = uas_probe,
.disconnect = uas_disconnect,
.pre_reset = uas_pre_reset,
.post_reset = uas_post_reset,
.suspend = uas_suspend,
.resume = uas_resume,
.reset_resume = uas_reset_resume,
.drvwrap.driver.shutdown = uas_shutdown,
.id_table = uas_usb_ids,
};
module_usb_driver(uas_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR(
"Hans de Goede <hdegoede@redhat.com>, Matthew Wilcox and Sarah Sharp");
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2911_1 |
crossvul-cpp_data_good_3412_0 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Copyright (c) 2009 by Krzysztof Helt
* Routines for control of MPU-401 in UART mode
*
* MPU-401 supports UART mode which is not capable generate transmit
* interrupts thus output is done via polling. Also, if irq < 0, then
* input is done also via polling. Do not expect good performance.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/rawmidi.h>
#include "msnd.h"
#define MSNDMIDI_MODE_BIT_INPUT 0
#define MSNDMIDI_MODE_BIT_OUTPUT 1
#define MSNDMIDI_MODE_BIT_INPUT_TRIGGER 2
#define MSNDMIDI_MODE_BIT_OUTPUT_TRIGGER 3
struct snd_msndmidi {
struct snd_msnd *dev;
unsigned long mode; /* MSNDMIDI_MODE_XXXX */
struct snd_rawmidi_substream *substream_input;
spinlock_t input_lock;
};
/*
* input/output open/close - protected by open_mutex in rawmidi.c
*/
static int snd_msndmidi_input_open(struct snd_rawmidi_substream *substream)
{
struct snd_msndmidi *mpu;
snd_printdd("snd_msndmidi_input_open()\n");
mpu = substream->rmidi->private_data;
mpu->substream_input = substream;
snd_msnd_enable_irq(mpu->dev);
snd_msnd_send_dsp_cmd(mpu->dev, HDEX_MIDI_IN_START);
set_bit(MSNDMIDI_MODE_BIT_INPUT, &mpu->mode);
return 0;
}
static int snd_msndmidi_input_close(struct snd_rawmidi_substream *substream)
{
struct snd_msndmidi *mpu;
mpu = substream->rmidi->private_data;
snd_msnd_send_dsp_cmd(mpu->dev, HDEX_MIDI_IN_STOP);
clear_bit(MSNDMIDI_MODE_BIT_INPUT, &mpu->mode);
mpu->substream_input = NULL;
snd_msnd_disable_irq(mpu->dev);
return 0;
}
static void snd_msndmidi_input_drop(struct snd_msndmidi *mpu)
{
u16 tail;
tail = readw(mpu->dev->MIDQ + JQS_wTail);
writew(tail, mpu->dev->MIDQ + JQS_wHead);
}
/*
* trigger input
*/
static void snd_msndmidi_input_trigger(struct snd_rawmidi_substream *substream,
int up)
{
unsigned long flags;
struct snd_msndmidi *mpu;
snd_printdd("snd_msndmidi_input_trigger(, %i)\n", up);
mpu = substream->rmidi->private_data;
spin_lock_irqsave(&mpu->input_lock, flags);
if (up) {
if (!test_and_set_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER,
&mpu->mode))
snd_msndmidi_input_drop(mpu);
} else {
clear_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER, &mpu->mode);
}
spin_unlock_irqrestore(&mpu->input_lock, flags);
if (up)
snd_msndmidi_input_read(mpu);
}
void snd_msndmidi_input_read(void *mpuv)
{
unsigned long flags;
struct snd_msndmidi *mpu = mpuv;
void *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF;
u16 head, tail, size;
spin_lock_irqsave(&mpu->input_lock, flags);
head = readw(mpu->dev->MIDQ + JQS_wHead);
tail = readw(mpu->dev->MIDQ + JQS_wTail);
size = readw(mpu->dev->MIDQ + JQS_wSize);
if (head > size || tail > size)
goto out;
while (head != tail) {
unsigned char val = readw(pwMIDQData + 2 * head);
if (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER, &mpu->mode))
snd_rawmidi_receive(mpu->substream_input, &val, 1);
if (++head > size)
head = 0;
writew(head, mpu->dev->MIDQ + JQS_wHead);
}
out:
spin_unlock_irqrestore(&mpu->input_lock, flags);
}
EXPORT_SYMBOL(snd_msndmidi_input_read);
static const struct snd_rawmidi_ops snd_msndmidi_input = {
.open = snd_msndmidi_input_open,
.close = snd_msndmidi_input_close,
.trigger = snd_msndmidi_input_trigger,
};
static void snd_msndmidi_free(struct snd_rawmidi *rmidi)
{
struct snd_msndmidi *mpu = rmidi->private_data;
kfree(mpu);
}
int snd_msndmidi_new(struct snd_card *card, int device)
{
struct snd_msnd *chip = card->private_data;
struct snd_msndmidi *mpu;
struct snd_rawmidi *rmidi;
int err;
err = snd_rawmidi_new(card, "MSND-MIDI", device, 1, 1, &rmidi);
if (err < 0)
return err;
mpu = kzalloc(sizeof(*mpu), GFP_KERNEL);
if (mpu == NULL) {
snd_device_free(card, rmidi);
return -ENOMEM;
}
mpu->dev = chip;
chip->msndmidi_mpu = mpu;
rmidi->private_data = mpu;
rmidi->private_free = snd_msndmidi_free;
spin_lock_init(&mpu->input_lock);
strcpy(rmidi->name, "MSND MIDI");
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
&snd_msndmidi_input);
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_INPUT;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3412_0 |
crossvul-cpp_data_good_2935_0 | /* radare - LGPL - Copyright 2012-2017 - pancake, Fedor Sakharov */
#define D0 if(1)
#define D1 if(1)
#include <errno.h>
#define DWARF_DUMP 0
#if DWARF_DUMP
#define DBGFD stdout
#else
#define DBGFD NULL
#endif
#include <r_bin.h>
#include <r_bin_dwarf.h>
#include <r_core.h>
#define STANDARD_OPERAND_COUNT_DWARF2 9
#define STANDARD_OPERAND_COUNT_DWARF3 12
#define R_BIN_DWARF_INFO 1
#define READ(x,y) ((x + sizeof (y) < buf_end)? *((y*)x): 0); x += sizeof (y)
static const char *dwarf_tag_name_encodings[] = {
[DW_TAG_array_type] = "DW_TAG_array_type",
[DW_TAG_class_type] = "DW_TAG_class_type",
[DW_TAG_entry_point] = "DW_TAG_entry_point",
[DW_TAG_enumeration_type] = "DW_TAG_enumeration_type",
[DW_TAG_formal_parameter] = "DW_TAG_formal_parameter",
[DW_TAG_imported_declaration] = "DW_TAG_imported_declaration",
[DW_TAG_label] = "DW_TAG_label",
[DW_TAG_lexical_block] = "DW_TAG_lexical_block",
[DW_TAG_member] = "DW_TAG_member",
[DW_TAG_pointer_type] = "DW_TAG_pointer_type",
[DW_TAG_reference_type] = "DW_TAG_reference_type",
[DW_TAG_compile_unit] = "DW_TAG_compile_unit",
[DW_TAG_string_type] = "DW_TAG_string_type",
[DW_TAG_structure_type] = "DW_TAG_structure_type",
[DW_TAG_subroutine_type] = "DW_TAG_subroutine_type",
[DW_TAG_typedef] = "DW_TAG_typedef",
[DW_TAG_union_type] = "DW_TAG_union_type",
[DW_TAG_unspecified_parameters] = "DW_TAG_unspecified_parameters",
[DW_TAG_variant] = "DW_TAG_variant",
[DW_TAG_common_block] = "DW_TAG_common_block",
[DW_TAG_common_inclusion] = "DW_TAG_common_inclusion",
[DW_TAG_inheritance] = "DW_TAG_inheritance",
[DW_TAG_inlined_subroutine] = "DW_TAG_inlined_subroutine",
[DW_TAG_module] = "DW_TAG_module",
[DW_TAG_ptr_to_member_type] = "DW_TAG_ptr_to_member_type",
[DW_TAG_set_type] = "DW_TAG_set_type",
[DW_TAG_subrange_type] = "DW_TAG_subrange_type",
[DW_TAG_with_stmt] = "DW_TAG_with_stmt",
[DW_TAG_access_declaration] = "DW_TAG_access_declaration",
[DW_TAG_base_type] = "DW_TAG_base_type",
[DW_TAG_catch_block] = "DW_TAG_catch_block",
[DW_TAG_const_type] = "DW_TAG_const_type",
[DW_TAG_constant] = "DW_TAG_constant",
[DW_TAG_enumerator] = "DW_TAG_enumerator",
[DW_TAG_file_type] = "DW_TAG_file_type",
[DW_TAG_friend] = "DW_TAG_friend",
[DW_TAG_namelist] = "DW_TAG_namelist",
[DW_TAG_namelist_item] = "DW_TAG_namelist_item",
[DW_TAG_packed_type] = "DW_TAG_packed_type",
[DW_TAG_subprogram] = "DW_TAG_subprogram",
[DW_TAG_template_type_param] = "DW_TAG_template_type_param",
[DW_TAG_template_value_param] = "DW_TAG_template_value_param",
[DW_TAG_template_alias] = "DW_TAG_template_alias",
[DW_TAG_thrown_type] = "DW_TAG_thrown_type",
[DW_TAG_try_block] = "DW_TAG_try_block",
[DW_TAG_variant_part] = "DW_TAG_variant_part",
[DW_TAG_variable] = "DW_TAG_variable",
[DW_TAG_volatile_type] = "DW_TAG_volatile_type"
};
static const char *dwarf_attr_encodings[] = {
[DW_AT_sibling] = "DW_AT_siblings",
[DW_AT_location] = "DW_AT_location",
[DW_AT_name] = "DW_AT_name",
[DW_AT_ordering] = "DW_AT_ordering",
[DW_AT_byte_size] = "DW_AT_byte_size",
[DW_AT_bit_size] = "DW_AT_bit_size",
[DW_AT_stmt_list] = "DW_AT_stmt_list",
[DW_AT_low_pc] = "DW_AT_low_pc",
[DW_AT_high_pc] = "DW_AT_high_pc",
[DW_AT_language] = "DW_AT_language",
[DW_AT_discr] = "DW_AT_discr",
[DW_AT_discr_value] = "DW_AT_discr_value",
[DW_AT_visibility] = "DW_AT_visibility",
[DW_AT_import] = "DW_AT_import",
[DW_AT_string_length] = "DW_AT_string_length",
[DW_AT_common_reference] = "DW_AT_common_reference",
[DW_AT_comp_dir] = "DW_AT_comp_dir",
[DW_AT_const_value] = "DW_AT_const_value",
[DW_AT_containing_type] = "DW_AT_containig_type",
[DW_AT_default_value] = "DW_AT_default_value",
[DW_AT_inline] = "DW_AT_inline",
[DW_AT_is_optional] = "DW_AT_is_optional",
[DW_AT_lower_bound] = "DW_AT_lower_bound",
[DW_AT_producer] = "DW_AT_producer",
[DW_AT_prototyped] = "DW_AT_prototyped",
[DW_AT_return_addr] = "DW_AT_return_addr",
[DW_AT_start_scope] = "DW_AT_start_scope",
[DW_AT_stride_size] = "DW_AT_stride_size",
[DW_AT_upper_bound] = "DW_AT_upper_bound",
[DW_AT_abstract_origin] = "DW_AT_abstract_origin",
[DW_AT_accessibility] = "DW_AT_accessibility",
[DW_AT_address_class] = "DW_AT_address_class",
[DW_AT_artificial] = "DW_AT_artificial",
[DW_AT_base_types] = "DW_AT_base_types",
[DW_AT_calling_convention] = "DW_AT_calling_convention",
[DW_AT_count] = "DW_AT_count",
[DW_AT_data_member_location] = "DW_AT_data_member_location",
[DW_AT_decl_column] = "DW_AT_decl_column",
[DW_AT_decl_file] = "DW_AT_decl_file",
[DW_AT_decl_line] = "DW_AT_decl_line",
[DW_AT_declaration] = "DW_AT_declaration",
[DW_AT_discr_list] = "DW_AT_discr_list",
[DW_AT_encoding] = "DW_AT_encoding",
[DW_AT_external] = "DW_AT_external",
[DW_AT_frame_base] = "DW_AT_frame_base",
[DW_AT_friend] = "DW_AT_friend",
[DW_AT_identifier_case] = "DW_AT_identifier_case",
[DW_AT_macro_info] = "DW_AT_macro_info",
[DW_AT_namelist_item] = "DW_AT_namelist_item",
[DW_AT_priority] = "DW_AT_priority",
[DW_AT_segment] = "DW_AT_segment",
[DW_AT_specification] = "DW_AT_specification",
[DW_AT_static_link] = "DW_AT_static_link",
[DW_AT_type] = "DW_AT_type",
[DW_AT_use_location] = "DW_AT_use_location",
[DW_AT_variable_parameter] = "DW_AT_variable_parameter",
[DW_AT_virtuality] = "DW_AT_virtuality",
[DW_AT_vtable_elem_location] = "DW_AT_vtable_elem_location"
};
static const char *dwarf_attr_form_encodings[] = {
[DW_FORM_addr] = "DW_FORM_addr",
[DW_FORM_block2] = "DW_FORM_block2",
[DW_FORM_block4] = "DW_FORM_block4",
[DW_FORM_data2] = "DW_FORM_data2",
[DW_FORM_data4] = "DW_FORM_data4",
[DW_FORM_data8] = "DW_FORM_data8",
[DW_FORM_string] = "DW_FORM_string",
[DW_FORM_block] = "DW_FORM_block",
[DW_FORM_block1] = "DW_FORM_block1",
[DW_FORM_data1] = "DW_FORM_data1",
[DW_FORM_flag] = "DW_FORM_flag",
[DW_FORM_sdata] = "DW_FORM_sdata",
[DW_FORM_strp] = "DW_FORM_strp",
[DW_FORM_udata] = "DW_FORM_udata",
[DW_FORM_ref_addr] = "DW_FORM_ref_addr",
[DW_FORM_ref1] = "DW_FORM_ref1",
[DW_FORM_ref2] = "DW_FORM_ref2",
[DW_FORM_ref4] = "DW_FORM_ref4",
[DW_FORM_ref8] = "DW_FORM_ref8",
[DW_FORM_ref_udata] = "DW_FORM_ref_udata",
[DW_FORM_indirect] = "DW_FORM_indirect"
};
static const char *dwarf_langs[] = {
[DW_LANG_C89] = "C89",
[DW_LANG_C] = "C",
[DW_LANG_Ada83] = "Ada83",
[DW_LANG_C_plus_plus] = "C++",
[DW_LANG_Cobol74] = "Cobol74",
[DW_LANG_Cobol85] = "Cobol85",
[DW_LANG_Fortran77] = "Fortran77",
[DW_LANG_Fortran90] = "Fortran90",
[DW_LANG_Pascal83] = "Pascal83",
[DW_LANG_Modula2] = "Modula2",
[DW_LANG_Java] = "Java",
[DW_LANG_C99] = "C99",
[DW_LANG_Ada95] = "Ada95",
[DW_LANG_Fortran95] = "Fortran95",
[DW_LANG_PLI] = "PLI",
[DW_LANG_ObjC] = "ObjC",
[DW_LANG_ObjC_plus_plus] = "ObjC_plus_plus",
[DW_LANG_UPC] = "UPC",
[DW_LANG_D] = "D",
[DW_LANG_Python] = "Python",
[DW_LANG_Rust] = "Rust",
[DW_LANG_C11] = "C11",
[DW_LANG_Swift] = "Swift",
[DW_LANG_Julia] = "Julia",
[DW_LANG_Dylan] = "Dylan",
[DW_LANG_C_plus_plus_14] = "C++14",
[DW_LANG_Fortran03] = "Fortran03",
[DW_LANG_Fortran08] = "Fortran08"
};
static int add_sdb_include_dir(Sdb *s, const char *incl, int idx) {
if (!s || !incl)
return false;
return sdb_array_set (s, "includedirs", idx, incl, 0);
}
static const ut8 *r_bin_dwarf_parse_lnp_header (
RBinFile *bf, const ut8 *buf, const ut8 *buf_end,
RBinDwarfLNPHeader *hdr, FILE *f, int mode) {
int i;
Sdb *s;
size_t count;
const ut8 *tmp_buf = NULL;
if (!hdr || !bf || !buf) return NULL;
hdr->unit_length.part1 = READ (buf, ut32);
if (hdr->unit_length.part1 == DWARF_INIT_LEN_64) {
hdr->unit_length.part2 = READ (buf, ut32);
}
s = sdb_new (NULL, NULL, 0);
hdr->version = READ (buf, ut16);
if (hdr->unit_length.part1 == DWARF_INIT_LEN_64) {
hdr->header_length = READ (buf, ut64);
} else {
hdr->header_length = READ (buf, ut32);
}
if (buf_end-buf < 8) {
sdb_free (s);
return NULL;
}
hdr->min_inst_len = READ (buf, ut8);
//hdr->max_ops_per_inst = READ (buf, ut8);
hdr->file_names = NULL;
hdr->default_is_stmt = READ (buf, ut8);
hdr->line_base = READ (buf, char);
hdr->line_range = READ (buf, ut8);
hdr->opcode_base = READ (buf, ut8);
if (f) {
fprintf (f, "DWARF LINE HEADER\n");
fprintf (f, " total_length: %d\n", hdr->unit_length.part1);
fprintf (f, " version: %d\n", hdr->version);
fprintf (f, " header_length: : %"PFMT64d"\n", hdr->header_length);
fprintf (f, " mininstlen: %d\n", hdr->min_inst_len);
fprintf (f, " is_stmt: %d\n", hdr->default_is_stmt);
fprintf (f, " line_base: %d\n", hdr->line_base);
fprintf (f, " line_range: %d\n", hdr->line_range);
fprintf (f, " opcode_base: %d\n", hdr->opcode_base);
}
if (hdr->opcode_base>0) {
hdr->std_opcode_lengths = calloc(sizeof(ut8), hdr->opcode_base);
for (i = 1; i <= hdr->opcode_base - 1; i++) {
if (buf+2>buf_end) break;
hdr->std_opcode_lengths[i] = READ (buf, ut8);
if (f) {
fprintf (f, " op %d %d\n", i, hdr->std_opcode_lengths[i]);
}
}
} else {
hdr->std_opcode_lengths = NULL;
}
i = 0;
while (buf+1 < buf_end) {
int maxlen = R_MIN ((size_t)(buf_end-buf)-1, 0xfff);
int len = r_str_nlen ((const char*)buf, maxlen);
char *str = r_str_ndup ((const char *)buf, len);
if (len<1 || len >= 0xfff) {
buf += 1;
free (str);
break;
}
if (*str != '/' && *str != '.') {
// no more paths in here
free (str);
break;
}
if (f) {
fprintf (f, "INCLUDEDIR (%s)\n", str);
}
add_sdb_include_dir (s, str, i);
free (str);
i++;
buf += len + 1;
}
tmp_buf = buf;
count = 0;
for (i = 0; i < 2; i++) {
while (buf+1<buf_end) {
const char *filename = (const char *)buf;
int maxlen = R_MIN ((size_t)(buf_end-buf-1), 0xfff);
ut64 id_idx, mod_time, file_len;
size_t namelen, len = r_str_nlen (filename, maxlen);
if (!len) {
buf++;
break;
}
buf += len + 1;
if (buf>=buf_end) { buf = NULL; goto beach; }
buf = r_uleb128 (buf, buf_end-buf, &id_idx);
if (buf>=buf_end) { buf = NULL; goto beach; }
buf = r_uleb128 (buf, buf_end-buf, &mod_time);
if (buf>=buf_end) { buf = NULL; goto beach; }
buf = r_uleb128 (buf, buf_end-buf, &file_len);
if (buf>=buf_end) { buf = NULL; goto beach; }
if (i) {
char *include_dir = NULL, *comp_dir = NULL;
char *allocated_id = NULL;
if (id_idx > 0) {
include_dir = sdb_array_get (s, "includedirs", id_idx - 1, 0);
if (include_dir && include_dir[0] != '/') {
comp_dir = sdb_get (bf->sdb_addrinfo, "DW_AT_comp_dir", 0);
if (comp_dir) {
allocated_id = calloc (1, strlen (comp_dir) +
strlen (include_dir) + 8);
snprintf (allocated_id, strlen (comp_dir) + strlen (include_dir) + 8,
"%s/%s/", comp_dir, include_dir);
include_dir = allocated_id;
}
}
} else {
include_dir = sdb_get (bf->sdb_addrinfo, "DW_AT_comp_dir", 0);
if (!include_dir)
include_dir = "./";
}
namelen = len + (include_dir?strlen (include_dir):0) + 8;
if (hdr->file_names) {
hdr->file_names[count].name = calloc (sizeof(char), namelen);
snprintf (hdr->file_names[count].name, namelen - 1,
"%s/%s", include_dir? include_dir : "", filename);
hdr->file_names[count].name[namelen - 1] = '\0';
free (allocated_id);
hdr->file_names[count].id_idx = id_idx;
hdr->file_names[count].mod_time = mod_time;
hdr->file_names[count].file_len = file_len;
}
}
count++;
if (f && i) {
fprintf (f, "FILE (%s)\n", filename);
fprintf (f, "| dir idx %"PFMT64d"\n", id_idx);
fprintf (f, "| lastmod %"PFMT64d"\n", mod_time);
fprintf (f, "| filelen %"PFMT64d"\n", file_len);
}
}
if (i == 0) {
if (count>0) {
hdr->file_names = calloc(sizeof(file_entry), count);
} else {
hdr->file_names = NULL;
}
hdr->file_names_count = count;
buf = tmp_buf;
count = 0;
}
}
beach:
sdb_free (s);
return buf;
}
static inline void add_sdb_addrline(Sdb *s, ut64 addr, const char *file, ut64 line, FILE *f, int mode) {
const char *p;
char *fileline;
char offset[64];
char *offset_ptr;
if (!s || !file)
return;
p = r_str_rchr (file, NULL, '/');
if (p) {
p++;
} else {
p = file;
}
// includedirs and properly check full paths
switch (mode) {
case 1:
case 'r':
case '*':
if (!f) {
f = stdout;
}
fprintf (f, "CL %s:%d 0x%08"PFMT64x"\n", p, (int)line, addr);
break;
}
#if 0
/* THIS IS TOO SLOW */
if (r_file_exists (file)) {
p = file;
}
#else
p = file;
#endif
fileline = r_str_newf ("%s|%"PFMT64d, p, line);
offset_ptr = sdb_itoa (addr, offset, 16);
sdb_add (s, offset_ptr, fileline, 0);
sdb_add (s, fileline, offset_ptr, 0);
free (fileline);
}
static const ut8* r_bin_dwarf_parse_ext_opcode(const RBin *a, const ut8 *obuf,
size_t len, const RBinDwarfLNPHeader *hdr,
RBinDwarfSMRegisters *regs, FILE *f, int mode) {
// XXX - list is an unused parameter.
const ut8 *buf;
const ut8 *buf_end;
ut8 opcode;
ut64 addr;
buf = obuf;
st64 op_len;
RBinFile *binfile = a ? a->cur : NULL;
RBinObject *o = binfile ? binfile->o : NULL;
ut32 addr_size = o && o->info && o->info->bits ? o->info->bits / 8 : 4;
const char *filename;
if (!binfile || !obuf || !hdr || !regs) return NULL;
buf = r_leb128 (buf, &op_len);
buf_end = buf+len;
opcode = *buf++;
if (f) {
fprintf (f, "Extended opcode %d: ", opcode);
}
switch (opcode) {
case DW_LNE_end_sequence:
regs->end_sequence = DWARF_TRUE;
if (binfile && binfile->sdb_addrinfo && hdr->file_names) {
int fnidx = regs->file - 1;
if (fnidx >= 0 && fnidx < hdr->file_names_count) {
add_sdb_addrline(binfile->sdb_addrinfo, regs->address,
hdr->file_names[fnidx].name, regs->line, f, mode);
}
}
if (f) {
fprintf (f, "End of Sequence\n");
}
break;
case DW_LNE_set_address:
if (addr_size == 8) {
addr = READ (buf, ut64);
} else {
addr = READ (buf, ut32);
}
regs->address = addr;
if (f) {
fprintf (f, "set Address to 0x%"PFMT64x"\n", addr);
}
break;
case DW_LNE_define_file:
filename = (const char*)buf;
if (f) {
fprintf (f, "define_file\n");
fprintf (f, "filename %s\n", filename);
}
buf += (strlen (filename) + 1);
ut64 dir_idx;
if (buf+1 < buf_end)
buf = r_uleb128 (buf, ST32_MAX, &dir_idx);
break;
case DW_LNE_set_discriminator:
buf = r_uleb128 (buf, ST32_MAX, &addr);
if (f) {
fprintf (f, "set Discriminator to %"PFMT64d"\n", addr);
}
regs->discriminator = addr;
break;
default:
if (f) {
fprintf (f, "Unexpeced opcode %d\n", opcode);
}
break;
}
return buf;
}
static const ut8* r_bin_dwarf_parse_spec_opcode(
const RBin *a, const ut8 *obuf, size_t len,
const RBinDwarfLNPHeader *hdr,
RBinDwarfSMRegisters *regs,
ut8 opcode, FILE *f, int mode) {
// XXX - list is not used
const ut8 *buf = obuf;
ut8 adj_opcode = 0;
ut64 advance_adr;
RBinFile *binfile = a ? a->cur : NULL;
if (!obuf || !hdr || !regs) {
return NULL;
}
adj_opcode = opcode - hdr->opcode_base;
if (!hdr->line_range) {
// line line-range information. move away
return NULL;
}
advance_adr = adj_opcode / hdr->line_range;
regs->address += advance_adr;
regs->line += hdr->line_base + (adj_opcode % hdr->line_range);
if (f) {
fprintf (f, "Special opcode %d: ", adj_opcode);
fprintf (f, "advance Address by %"PFMT64d" to %"PFMT64x" and Line by %d to %"PFMT64d"\n",
advance_adr, regs->address, hdr->line_base +
(adj_opcode % hdr->line_range), regs->line);
}
if (binfile && binfile->sdb_addrinfo && hdr->file_names) {
int idx = regs->file -1;
if (idx >= 0 && idx < hdr->file_names_count) {
add_sdb_addrline (binfile->sdb_addrinfo, regs->address,
hdr->file_names[idx].name,
regs->line, f, mode);
}
}
regs->basic_block = DWARF_FALSE;
regs->prologue_end = DWARF_FALSE;
regs->epilogue_begin = DWARF_FALSE;
regs->discriminator = 0;
return buf;
}
static const ut8* r_bin_dwarf_parse_std_opcode(
const RBin *a, const ut8 *obuf, size_t len,
const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs,
ut8 opcode, FILE *f, int mode) {
const ut8* buf = obuf;
const ut8* buf_end = obuf + len;
ut64 addr = 0LL;
st64 sbuf;
ut8 adj_opcode;
ut64 op_advance;
ut16 operand;
RBinFile *binfile = a ? a->cur : NULL;
if (!binfile || !hdr || !regs || !obuf) {
return NULL;
}
switch (opcode) {
case DW_LNS_copy:
if (f) {
fprintf (f, "Copy\n");
}
if (binfile && binfile->sdb_addrinfo && hdr->file_names) {
int fnidx = regs->file - 1;
if (fnidx >= 0 && fnidx < hdr->file_names_count) {
add_sdb_addrline (binfile->sdb_addrinfo,
regs->address,
hdr->file_names[fnidx].name,
regs->line, f, mode);
}
}
regs->basic_block = DWARF_FALSE;
break;
case DW_LNS_advance_pc:
buf = r_uleb128 (buf, ST32_MAX, &addr);
regs->address += addr * hdr->min_inst_len;
if (f) {
fprintf (f, "Advance PC by %"PFMT64d" to 0x%"PFMT64x"\n",
addr * hdr->min_inst_len, regs->address);
}
break;
case DW_LNS_advance_line:
buf = r_leb128(buf, &sbuf);
regs->line += sbuf;
if (f) {
fprintf (f, "Advance line by %"PFMT64d", to %"PFMT64d"\n", sbuf, regs->line);
}
break;
case DW_LNS_set_file:
buf = r_uleb128 (buf, ST32_MAX, &addr);
if (f) {
fprintf (f, "Set file to %"PFMT64d"\n", addr);
}
regs->file = addr;
break;
case DW_LNS_set_column:
buf = r_uleb128 (buf, ST32_MAX, &addr);
if (f) {
fprintf (f, "Set column to %"PFMT64d"\n", addr);
}
regs->column = addr;
break;
case DW_LNS_negate_stmt:
regs->is_stmt = regs->is_stmt ? DWARF_FALSE : DWARF_TRUE;
if (f) {
fprintf (f, "Set is_stmt to %d\n", regs->is_stmt);
}
break;
case DW_LNS_set_basic_block:
if (f) {
fprintf (f, "set_basic_block\n");
}
regs->basic_block = DWARF_TRUE;
break;
case DW_LNS_const_add_pc:
adj_opcode = 255 - hdr->opcode_base;
if (hdr->line_range > 0) {
op_advance = adj_opcode / hdr->line_range;
} else {
op_advance = 0;
}
regs->address += op_advance;
if (f) {
fprintf (f, "Advance PC by constant %"PFMT64d" to 0x%"PFMT64x"\n",
op_advance, regs->address);
}
break;
case DW_LNS_fixed_advance_pc:
operand = READ (buf, ut16);
regs->address += operand;
if (f) {
fprintf (f,"Fixed advance pc to %"PFMT64d"\n", regs->address);
}
break;
case DW_LNS_set_prologue_end:
regs->prologue_end = ~0;
if (f) {
fprintf (f, "set_prologue_end\n");
}
break;
case DW_LNS_set_epilogue_begin:
regs->epilogue_begin = ~0;
if (f) {
fprintf (f, "set_epilogue_begin\n");
}
break;
case DW_LNS_set_isa:
buf = r_uleb128 (buf, ST32_MAX, &addr);
regs->isa = addr;
if (f) {
fprintf (f, "set_isa\n");
}
break;
default:
if (f) {
fprintf (f, "Unexpected opcode\n");
}
break;
}
return buf;
}
static const ut8* r_bin_dwarf_parse_opcodes(const RBin *a, const ut8 *obuf,
size_t len, const RBinDwarfLNPHeader *hdr,
RBinDwarfSMRegisters *regs, FILE *f, int mode) {
const ut8 *buf, *buf_end;
ut8 opcode, ext_opcode;
if (!a || !obuf || len < 8) {
return NULL;
}
buf = obuf;
buf_end = obuf + len;
while (buf && buf + 1 < buf_end) {
opcode = *buf++;
len--;
if (!opcode) {
ext_opcode = *buf;
buf = r_bin_dwarf_parse_ext_opcode (a, buf, len, hdr, regs, f, mode);
if (ext_opcode == DW_LNE_end_sequence) {
break;
}
} else if (opcode >= hdr->opcode_base) {
buf = r_bin_dwarf_parse_spec_opcode (a, buf, len, hdr, regs, opcode, f, mode);
} else {
buf = r_bin_dwarf_parse_std_opcode (a, buf, len, hdr, regs, opcode, f, mode);
}
len = (int)(buf_end - buf);
}
return buf;
}
static void r_bin_dwarf_set_regs_default (const RBinDwarfLNPHeader *hdr, RBinDwarfSMRegisters *regs) {
regs->address = 0;
regs->file = 1;
regs->line = 1;
regs->column = 0;
regs->is_stmt = hdr->default_is_stmt;
regs->basic_block = DWARF_FALSE;
regs->end_sequence = DWARF_FALSE;
}
R_API int r_bin_dwarf_parse_line_raw2(const RBin *a, const ut8 *obuf,
size_t len, int mode) {
RBinDwarfLNPHeader hdr = {{0}};
const ut8 *buf = NULL, *buf_tmp = NULL, *buf_end = NULL;
RBinDwarfSMRegisters regs;
int tmplen;
FILE *f = NULL;
RBinFile *binfile = a ? a->cur : NULL;
if (!binfile || !obuf) {
return false;
}
if (mode == R_CORE_BIN_PRINT) {
f = stdout;
}
buf = obuf;
buf_end = obuf + len;
while (buf + 1 < buf_end) {
buf_tmp = buf;
buf = r_bin_dwarf_parse_lnp_header (a->cur, buf, buf_end, &hdr, f, mode);
if (!buf) {
return false;
}
r_bin_dwarf_set_regs_default (&hdr, ®s);
tmplen = (int)(buf_end - buf);
tmplen = R_MIN (tmplen, 4 + hdr.unit_length.part1);
if (tmplen < 1) {
break;
}
if (!r_bin_dwarf_parse_opcodes (a, buf, tmplen, &hdr, ®s, f, mode)) {
break;
}
buf = buf_tmp + tmplen;
len = (int)(buf_end - buf);
}
return true;
}
#define READ_BUF(x,y) if (idx+sizeof(y)>=len) { return false;} \
x=*(y*)buf; idx+=sizeof(y);buf+=sizeof(y)
R_API int r_bin_dwarf_parse_aranges_raw(const ut8 *obuf, int len, FILE *f) {
ut32 length, offset;
ut16 version;
ut32 debug_info_offset;
ut8 address_size, segment_size;
const ut8 *buf = obuf;
int idx = 0;
if (!buf || len< 4) {
return false;
}
READ_BUF (length, ut32);
if (f) {
printf("parse_aranges\n");
printf("length 0x%x\n", length);
}
if (idx+12>=len)
return false;
READ_BUF (version, ut16);
if (f) {
printf("Version %d\n", version);
}
READ_BUF (debug_info_offset, ut32);
if (f) {
fprintf (f, "Debug info offset %d\n", debug_info_offset);
}
READ_BUF (address_size, ut8);
if (f) {
fprintf (f, "address size %d\n", (int)address_size);
}
READ_BUF (segment_size, ut8);
if (f) {
fprintf (f, "segment size %d\n", (int)segment_size);
}
offset = segment_size + address_size * 2;
if (offset) {
ut64 n = (((ut64) (size_t)buf / offset) + 1) * offset - ((ut64)(size_t)buf);
if (idx+n>=len) {
return false;
}
buf += n;
idx += n;
}
while ((buf - obuf) < len) {
ut64 adr, length;
if ((idx+8)>=len) {
break;
}
READ_BUF (adr, ut64);
READ_BUF (length, ut64);
if (f) printf("length 0x%"PFMT64x" address 0x%"PFMT64x"\n", length, adr);
}
return 0;
}
static int r_bin_dwarf_init_debug_info(RBinDwarfDebugInfo *inf) {
if (!inf) {
return -1;
}
inf->comp_units = calloc (sizeof (RBinDwarfCompUnit), DEBUG_INFO_CAPACITY);
// XXX - should we be using error codes?
if (!inf->comp_units) {
return -ENOMEM;
}
inf->capacity = DEBUG_INFO_CAPACITY;
inf->length = 0;
return true;
}
static int r_bin_dwarf_init_die(RBinDwarfDIE *die) {
if (!die) {
return -EINVAL;
}
die->attr_values = calloc (sizeof (RBinDwarfAttrValue), 8);
if (!die->attr_values) {
return -ENOMEM;
}
die->capacity = 8;
die->length = 0;
return 0;
}
static int r_bin_dwarf_expand_die(RBinDwarfDIE* die) {
RBinDwarfAttrValue *tmp = NULL;
if (!die || die->capacity == 0) {
return -EINVAL;
}
if (die->capacity != die->length) {
return -EINVAL;
}
tmp = (RBinDwarfAttrValue*)realloc (die->attr_values,
die->capacity * 2 * sizeof (RBinDwarfAttrValue));
if (!tmp) {
return -ENOMEM;
}
memset ((ut8*)tmp + die->capacity, 0, die->capacity);
die->attr_values = tmp;
die->capacity *= 2;
return 0;
}
static int r_bin_dwarf_init_comp_unit(RBinDwarfCompUnit *cu) {
if (!cu) {
return -EINVAL;
}
cu->dies = calloc (sizeof (RBinDwarfDIE), COMP_UNIT_CAPACITY);
if (!cu->dies) {
return -ENOMEM;
}
cu->capacity = COMP_UNIT_CAPACITY;
cu->length = 0;
return 0;
}
static int r_bin_dwarf_expand_cu(RBinDwarfCompUnit *cu) {
RBinDwarfDIE *tmp;
if (!cu || cu->capacity == 0 || cu->capacity != cu->length) {
return -EINVAL;
}
tmp = (RBinDwarfDIE*)realloc(cu->dies,
cu->capacity * 2 * sizeof(RBinDwarfDIE));
if (!tmp) {
return -ENOMEM;
}
memset ((ut8*)tmp + cu->capacity, 0, cu->capacity);
cu->dies = tmp;
cu->capacity *= 2;
return 0;
}
static int r_bin_dwarf_init_abbrev_decl(RBinDwarfAbbrevDecl *ad) {
if (!ad) {
return -EINVAL;
}
ad->specs = calloc (sizeof( RBinDwarfAttrSpec), ABBREV_DECL_CAP);
if (!ad->specs) {
return -ENOMEM;
}
ad->capacity = ABBREV_DECL_CAP;
ad->length = 0;
return 0;
}
static int r_bin_dwarf_expand_abbrev_decl(RBinDwarfAbbrevDecl *ad) {
RBinDwarfAttrSpec *tmp;
if (!ad || !ad->capacity || ad->capacity != ad->length) {
return -EINVAL;
}
tmp = (RBinDwarfAttrSpec*)realloc (ad->specs,
ad->capacity * 2 * sizeof (RBinDwarfAttrSpec));
if (!tmp) {
return -ENOMEM;
}
memset ((ut8*)tmp + ad->capacity, 0, ad->capacity);
ad->specs = tmp;
ad->capacity *= 2;
return 0;
}
static int r_bin_dwarf_init_debug_abbrev(RBinDwarfDebugAbbrev *da) {
if (!da) {
return -EINVAL;
}
da->decls = calloc (sizeof (RBinDwarfAbbrevDecl), DEBUG_ABBREV_CAP);
if (!da->decls) {
return -ENOMEM;
}
da->capacity = DEBUG_ABBREV_CAP;
da->length = 0;
return 0;
}
static int r_bin_dwarf_expand_debug_abbrev(RBinDwarfDebugAbbrev *da) {
RBinDwarfAbbrevDecl *tmp;
if (!da || da->capacity == 0 || da->capacity != da->length) {
return -EINVAL;
}
tmp = (RBinDwarfAbbrevDecl*)realloc (da->decls,
da->capacity * 2 * sizeof (RBinDwarfAbbrevDecl));
if (!tmp) {
return -ENOMEM;
}
memset ((ut8*)tmp + da->capacity, 0, da->capacity);
da->decls = tmp;
da->capacity *= 2;
return 0;
}
static void dump_r_bin_dwarf_debug_abbrev(FILE *f, RBinDwarfDebugAbbrev *da) {
size_t i, j;
ut64 attr_name, attr_form;
if (!f || !da) {
return;
}
for (i = 0; i < da->length; i++) {
int declstag = da->decls[i].tag;
fprintf (f, "Abbreviation Code %"PFMT64d" ", da->decls[i].code);
if (declstag>=0 && declstag < DW_TAG_LAST) {
fprintf (f, "Tag %s ", dwarf_tag_name_encodings[declstag]);
}
fprintf (f, "[%s]\n", da->decls[i].has_children ?
"has children" : "no children");
fprintf (f, "Offset 0x%"PFMT64x"\n", da->decls[i].offset);
for (j = 0; j < da->decls[i].length; j++) {
attr_name = da->decls[i].specs[j].attr_name;
attr_form = da->decls[i].specs[j].attr_form;
if (attr_name && attr_form &&
attr_name <= DW_AT_vtable_elem_location &&
attr_form <= DW_FORM_indirect) {
fprintf (f, " %s %s\n",
dwarf_attr_encodings[attr_name],
dwarf_attr_form_encodings[attr_form]);
}
}
}
}
R_API void r_bin_dwarf_free_debug_abbrev(RBinDwarfDebugAbbrev *da) {
size_t i;
if (!da) return;
for (i = 0; i < da->length; i++) {
R_FREE (da->decls[i].specs);
}
R_FREE (da->decls);
}
static void r_bin_dwarf_free_attr_value(RBinDwarfAttrValue *val) {
if (!val) {
return;
}
switch (val->form) {
case DW_FORM_strp:
case DW_FORM_string:
R_FREE (val->encoding.str_struct.string);
break;
case DW_FORM_block:
case DW_FORM_block1:
case DW_FORM_block2:
case DW_FORM_block4:
R_FREE (val->encoding.block.data);
break;
default:
break;
};
}
static void r_bin_dwarf_free_die(RBinDwarfDIE *die) {
size_t i;
if (!die) {
return;
}
for (i = 0; i < die->length; i++) {
r_bin_dwarf_free_attr_value (&die->attr_values[i]);
}
R_FREE (die->attr_values);
}
static void r_bin_dwarf_free_comp_unit(RBinDwarfCompUnit *cu) {
size_t i;
if (!cu) {
return;
}
for (i = 0; i < cu->length; i++) {
if (cu->dies) {
r_bin_dwarf_free_die (&cu->dies[i]);
}
}
R_FREE (cu->dies);
}
static void r_bin_dwarf_free_debug_info (RBinDwarfDebugInfo *inf) {
size_t i;
if (!inf) {
return;
}
for (i = 0; i < inf->length; i++) {
r_bin_dwarf_free_comp_unit (&inf->comp_units[i]);
}
R_FREE (inf->comp_units);
}
static void r_bin_dwarf_dump_attr_value(const RBinDwarfAttrValue *val, FILE *f) {
size_t i;
if (!val || !f) {
return;
}
switch (val->form) {
case DW_FORM_addr:
fprintf (f, "0x%"PFMT64x"", val->encoding.address);
break;
case DW_FORM_block:
case DW_FORM_block1:
case DW_FORM_block2:
case DW_FORM_block4:
fprintf (f, "%"PFMT64u" byte block:", val->encoding.block.length);
for (i = 0; i < val->encoding.block.length; i++) {
fprintf (f, "%02x", val->encoding.block.data[i]);
}
break;
case DW_FORM_data1:
case DW_FORM_data2:
case DW_FORM_data4:
case DW_FORM_data8:
fprintf (f, "%"PFMT64u"", val->encoding.data);
if (val->name == DW_AT_language) {
fprintf (f, " (%s)", dwarf_langs[val->encoding.data]);
}
break;
case DW_FORM_strp:
fprintf (f, "(indirect string, offset: 0x%"PFMT64x"): ",
val->encoding.str_struct.offset);
case DW_FORM_string:
if (val->encoding.str_struct.string) {
fprintf (f, "%s", val->encoding.str_struct.string);
} else {
fprintf (f, "No string found");
}
break;
case DW_FORM_flag:
fprintf (f, "%u", val->encoding.flag);
break;
case DW_FORM_sdata:
fprintf (f, "%"PFMT64d"", val->encoding.sdata);
break;
case DW_FORM_udata:
fprintf (f, "%"PFMT64u"", val->encoding.data);
break;
case DW_FORM_ref_addr:
fprintf (f, "<0x%"PFMT64x">", val->encoding.reference);
break;
case DW_FORM_ref1:
case DW_FORM_ref2:
case DW_FORM_ref4:
case DW_FORM_ref8:
fprintf (f, "<0x%"PFMT64x">", val->encoding.reference);
break;
default:
fprintf (f, "Unknown attr value form %"PFMT64d"\n", val->form);
};
}
static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name) {
continue;
}
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len,
RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value,
const RBinDwarfCompUnitHdr *hdr,
const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf;
const ut8 *buf_end = obuf + obuf_len;
size_t j;
if (!spec || !value || !hdr || !obuf || obuf_len < 1) {
return NULL;
}
value->form = spec->attr_form;
value->name = spec->attr_name;
value->encoding.block.data = NULL;
value->encoding.str_struct.string = NULL;
value->encoding.str_struct.offset = 0;
switch (spec->attr_form) {
case DW_FORM_addr:
switch (hdr->pointer_size) {
case 1:
value->encoding.address = READ (buf, ut8);
break;
case 2:
value->encoding.address = READ (buf, ut16);
break;
case 4:
value->encoding.address = READ (buf, ut32);
break;
case 8:
value->encoding.address = READ (buf, ut64);
break;
default:
eprintf ("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size);
return NULL;
}
break;
case DW_FORM_block2:
value->encoding.block.length = READ (buf, ut16);
if (value->encoding.block.length > 0) {
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block4:
value->encoding.block.length = READ (buf, ut32);
if (value->encoding.block.length > 0) {
ut8 *data = calloc (sizeof (ut8), value->encoding.block.length);
if (data) {
for (j = 0; j < value->encoding.block.length; j++) {
data[j] = READ (buf, ut8);
}
}
value->encoding.block.data = data;
}
break;
#if 0
// This causes segfaults to happen
case DW_FORM_data2:
value->encoding.data = READ (buf, ut16);
break;
case DW_FORM_data4:
value->encoding.data = READ (buf, ut32);
break;
case DW_FORM_data8:
value->encoding.data = READ (buf, ut64);
break;
#endif
case DW_FORM_string:
value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL;
buf += (strlen ((const char*)buf) + 1);
break;
case DW_FORM_block:
buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length);
if (!buf) {
return NULL;
}
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length);
if (value->encoding.block.data) {
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block1:
value->encoding.block.length = READ (buf, ut8);
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1);
if (value->encoding.block.data) {
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_flag:
value->encoding.flag = READ (buf, ut8);
break;
case DW_FORM_sdata:
buf = r_leb128 (buf, &value->encoding.sdata);
break;
case DW_FORM_strp:
value->encoding.str_struct.offset = READ (buf, ut32);
if (debug_str && value->encoding.str_struct.offset < debug_str_len) {
value->encoding.str_struct.string = strdup (
(const char *)(debug_str +
value->encoding.str_struct.offset));
} else {
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_udata:
{
ut64 ndata = 0;
const ut8 *data = (const ut8*)&ndata;
buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata);
memcpy (&value->encoding.data, data, sizeof (value->encoding.data));
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_ref_addr:
value->encoding.reference = READ (buf, ut64); // addr size of machine
break;
case DW_FORM_ref1:
value->encoding.reference = READ (buf, ut8);
break;
case DW_FORM_ref2:
value->encoding.reference = READ (buf, ut16);
break;
case DW_FORM_ref4:
value->encoding.reference = READ (buf, ut32);
break;
case DW_FORM_ref8:
value->encoding.reference = READ (buf, ut64);
break;
case DW_FORM_data1:
value->encoding.data = READ (buf, ut8);
break;
default:
eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form);
value->encoding.data = 0;
return NULL;
}
return buf;
}
static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
size_t offset, const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
ut64 abbr_code;
size_t i;
if (cu->hdr.length > debug_str_len) {
//avoid oob read
return NULL;
}
while (buf && buf < buf_end && buf >= obuf) {
if (cu->length && cu->capacity == cu->length) {
r_bin_dwarf_expand_cu (cu);
}
buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
if (abbr_code > da->length || !buf) {
return NULL;
}
r_bin_dwarf_init_die (&cu->dies[cu->length]);
if (!abbr_code) {
cu->dies[cu->length].abbrev_code = 0;
cu->length++;
buf++;
continue;
}
cu->dies[cu->length].abbrev_code = abbr_code;
cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
abbr_code += offset;
if (da->capacity < abbr_code) {
return NULL;
}
for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
r_bin_dwarf_expand_die (&cu->dies[cu->length]);
}
if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
break;
}
memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i]));
buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
&da->decls[abbr_code - 1].specs[i],
&cu->dies[cu->length].attr_values[i],
&cu->hdr, debug_str, debug_str_len);
if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
sdb_set (s, "DW_AT_comp_dir", name, 0);
}
cu->dies[cu->length].length++;
}
cu->length++;
}
return buf;
}
R_API int r_bin_dwarf_parse_info_raw(Sdb *s, RBinDwarfDebugAbbrev *da,
const ut8 *obuf, size_t len,
const ut8 *debug_str, size_t debug_str_len, int mode) {
const ut8 *buf = obuf, *buf_end = obuf + len;
size_t k, offset = 0;
int curr_unit = 0;
RBinDwarfDebugInfo di = {0};
RBinDwarfDebugInfo *inf = &di;
bool ret = true;
if (!da || !s || !obuf) {
return false;
}
if (r_bin_dwarf_init_debug_info (inf) < 0) {
ret = false;
goto out;
}
while (buf < buf_end) {
if (inf->length >= inf->capacity)
break;
if (r_bin_dwarf_init_comp_unit (&inf->comp_units[curr_unit]) < 0) {
ret = false;
curr_unit--;
goto out_debug_info;
}
inf->comp_units[curr_unit].offset = buf - obuf;
inf->comp_units[curr_unit].hdr.pointer_size = 0;
inf->comp_units[curr_unit].hdr.abbrev_offset = 0;
inf->comp_units[curr_unit].hdr.length = READ (buf, ut32);
inf->comp_units[curr_unit].hdr.version = READ (buf, ut16);
if (inf->comp_units[curr_unit].hdr.version != 2) {
// eprintf ("DWARF: version %d is not yet supported.\n",
// inf->comp_units[curr_unit].hdr.version);
ret = false;
goto out_debug_info;
}
if (inf->comp_units[curr_unit].hdr.length > len) {
ret = false;
goto out_debug_info;
}
inf->comp_units[curr_unit].hdr.abbrev_offset = READ (buf, ut32);
inf->comp_units[curr_unit].hdr.pointer_size = READ (buf, ut8);
inf->length++;
/* Linear search FIXME */
if (da->decls->length >= da->capacity) {
eprintf ("WARNING: malformed dwarf have not enough buckets for decls.\n");
}
const int k_max = R_MIN (da->capacity, da->decls->length);
for (k = 0; k < k_max; k++) {
if (da->decls[k].offset ==
inf->comp_units[curr_unit].hdr.abbrev_offset) {
offset = k;
break;
}
}
buf = r_bin_dwarf_parse_comp_unit (s, buf, &inf->comp_units[curr_unit],
da, offset, debug_str, debug_str_len);
if (!buf) {
ret = false;
goto out_debug_info;
}
curr_unit++;
}
if (mode == R_CORE_BIN_PRINT) {
r_bin_dwarf_dump_debug_info (NULL, inf);
}
out_debug_info:
for (; curr_unit >= 0; curr_unit--) {
r_bin_dwarf_free_comp_unit (&inf->comp_units[curr_unit]);
}
r_bin_dwarf_free_debug_info (inf);
out:
return ret;
}
static RBinDwarfDebugAbbrev *r_bin_dwarf_parse_abbrev_raw(const ut8 *obuf, size_t len, int mode) {
const ut8 *buf = obuf, *buf_end = obuf + len;
ut64 tmp, spec1, spec2, offset;
ut8 has_children;
RBinDwarfAbbrevDecl *tmpdecl;
// XXX - Set a suitable value here.
if (!obuf || len < 3) {
return NULL;
}
RBinDwarfDebugAbbrev *da = R_NEW0 (RBinDwarfDebugAbbrev);
r_bin_dwarf_init_debug_abbrev (da);
while (buf && buf+1 < buf_end) {
offset = buf - obuf;
buf = r_uleb128 (buf, (size_t)(buf_end-buf), &tmp);
if (!buf || !tmp) {
continue;
}
if (da->length == da->capacity) {
r_bin_dwarf_expand_debug_abbrev(da);
}
tmpdecl = &da->decls[da->length];
r_bin_dwarf_init_abbrev_decl (tmpdecl);
tmpdecl->code = tmp;
buf = r_uleb128 (buf, (size_t)(buf_end-buf), &tmp);
tmpdecl->tag = tmp;
tmpdecl->offset = offset;
if (buf >= buf_end) {
break;
}
has_children = READ (buf, ut8);
tmpdecl->has_children = has_children;
do {
if (tmpdecl->length == tmpdecl->capacity) {
r_bin_dwarf_expand_abbrev_decl (tmpdecl);
}
buf = r_uleb128 (buf, (size_t)(buf_end - buf), &spec1);
buf = r_uleb128 (buf, (size_t)(buf_end - buf), &spec2);
tmpdecl->specs[tmpdecl->length].attr_name = spec1;
tmpdecl->specs[tmpdecl->length].attr_form = spec2;
tmpdecl->length++;
} while (spec1 && spec2);
da->length++;
}
if (mode == R_CORE_BIN_PRINT) {
dump_r_bin_dwarf_debug_abbrev (stdout, da);
}
return da;
}
RBinSection *getsection(RBin *a, const char *sn) {
RListIter *iter;
RBinSection *section = NULL;
RBinFile *binfile = a ? a->cur: NULL;
RBinObject *o = binfile ? binfile->o : NULL;
if ( o && o->sections) {
r_list_foreach (o->sections, iter, section) {
if (strstr (section->name, sn)) {
return section;
}
}
}
return NULL;
}
R_API int r_bin_dwarf_parse_info(RBinDwarfDebugAbbrev *da, RBin *a, int mode) {
ut8 *buf, *debug_str_buf = 0;
int len, debug_str_len = 0, ret;
RBinSection *debug_str;
RBinSection *section = getsection (a, "debug_info");
RBinFile *binfile = a ? a->cur: NULL;
if (binfile && section) {
debug_str = getsection (a, "debug_str");
if (debug_str) {
debug_str_len = debug_str->size;
debug_str_buf = calloc (1, debug_str_len + 1);
ret = r_buf_read_at (binfile->buf, debug_str->paddr,
debug_str_buf, debug_str_len);
if (!ret) {
free (debug_str_buf);
return false;
}
}
len = section->size;
if (len > (UT32_MAX >> 1) || len < 1) {
free (debug_str_buf);
return false;
}
buf = calloc (1, len);
if (!buf) {
free (debug_str_buf);
return false;
}
if (!r_buf_read_at (binfile->buf, section->paddr, buf, len)) {
free (debug_str_buf);
free (buf);
return false;
}
ret = r_bin_dwarf_parse_info_raw (binfile->sdb_addrinfo, da, buf, len,
debug_str_buf, debug_str_len, mode);
R_FREE (debug_str_buf);
free (buf);
return ret;
}
return false;
}
static RBinDwarfRow *r_bin_dwarf_row_new (ut64 addr, const char *file, int line, int col) {
RBinDwarfRow *row = R_NEW0 (RBinDwarfRow);
if (!row) {
return NULL;
}
row->file = strdup (file);
row->address = addr;
row->line = line;
row->column = 0;
return row;
}
static void r_bin_dwarf_row_free(void *p) {
RBinDwarfRow *row = (RBinDwarfRow*)p;
free (row->file);
free (row);
}
R_API RList *r_bin_dwarf_parse_line(RBin *a, int mode) {
ut8 *buf;
RList *list = NULL;
int len, ret;
RBinSection *section = getsection (a, "debug_line");
RBinFile *binfile = a ? a->cur: NULL;
if (binfile && section) {
len = section->size;
if (len < 1) {
return NULL;
}
buf = calloc (1, len + 1);
if (!buf) {
return NULL;
}
ret = r_buf_read_at (binfile->buf, section->paddr, buf, len);
if (ret != len) {
free (buf);
return NULL;
}
list = r_list_new (); // always return empty list wtf
if (!list) {
free (buf);
return NULL;
}
list->free = r_bin_dwarf_row_free;
r_bin_dwarf_parse_line_raw2 (a, buf, len, mode);
// k bin/cur/addrinfo/*
SdbListIter *iter;
SdbKv *kv;
SdbList *ls = sdb_foreach_list (binfile->sdb_addrinfo, false);
ls_foreach (ls, iter, kv) {
if (!strncmp (kv->key, "0x", 2)) {
ut64 addr;
RBinDwarfRow *row;
int line;
char *file = strdup (kv->value);
if (!file) {
free (buf);
ls_free (ls);
r_list_free (list);
return NULL;
}
char *tok = strchr (file, '|');
if (tok) {
*tok++ = 0;
line = atoi (tok);
addr = r_num_math (NULL, kv->key);
row = r_bin_dwarf_row_new (addr, file, line, 0);
r_list_append (list, row);
}
free (file);
}
}
ls_free (ls);
free (buf);
}
return list;
}
R_API RList *r_bin_dwarf_parse_aranges(RBin *a, int mode) {
ut8 *buf;
int ret;
size_t len;
RBinSection *section = getsection (a, "debug_aranges");
RBinFile *binfile = a ? a->cur: NULL;
if (binfile && section) {
len = section->size;
if (len < 1 || len > ST32_MAX) {
return NULL;
}
buf = calloc (1, len);
ret = r_buf_read_at (binfile->buf, section->paddr, buf, len);
if (!ret) {
free (buf);
return NULL;
}
if (mode == R_CORE_BIN_PRINT) {
r_bin_dwarf_parse_aranges_raw (buf, len, stdout);
} else {
r_bin_dwarf_parse_aranges_raw (buf, len, DBGFD);
}
free (buf);
}
return NULL;
}
R_API RBinDwarfDebugAbbrev *r_bin_dwarf_parse_abbrev(RBin *a, int mode) {
ut8 *buf;
size_t len;
RBinSection *section = getsection (a, "debug_abbrev");
RBinDwarfDebugAbbrev *da = NULL;
RBinFile *binfile = a ? a->cur: NULL;
if (!section || !binfile) return NULL;
if (section->size > binfile->size) {
return NULL;
}
len = section->size;
buf = calloc (1,len);
r_buf_read_at (binfile->buf, section->paddr, buf, len);
da = r_bin_dwarf_parse_abbrev_raw (buf, len, mode);
free (buf);
return da;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2935_0 |
crossvul-cpp_data_bad_4496_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* RLE Compressed Bitmap Stream
*
* Copyright 2011 Jay Sorg <jay.sorg@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.
*/
/* do not compile the file directly */
/**
* Write a foreground/background image to a destination buffer.
*/
static INLINE BYTE* WRITEFGBGIMAGE(BYTE* pbDest, const BYTE* pbDestEnd, UINT32 rowDelta,
BYTE bitmask, PIXEL fgPel, INT32 cBits)
{
PIXEL xorPixel;
BYTE mask = 0x01;
if (cBits > 8)
return NULL;
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, cBits))
return NULL;
UNROLL(cBits, {
UINT32 data;
DESTREADPIXEL(xorPixel, pbDest - rowDelta);
if (bitmask & mask)
data = xorPixel ^ fgPel;
else
data = xorPixel;
DESTWRITEPIXEL(pbDest, data);
DESTNEXTPIXEL(pbDest);
mask = mask << 1;
});
return pbDest;
}
/**
* Write a foreground/background image to a destination buffer
* for the first line of compressed data.
*/
static INLINE BYTE* WRITEFIRSTLINEFGBGIMAGE(BYTE* pbDest, const BYTE* pbDestEnd, BYTE bitmask,
PIXEL fgPel, UINT32 cBits)
{
BYTE mask = 0x01;
if (cBits > 8)
return NULL;
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, cBits))
return NULL;
UNROLL(cBits, {
UINT32 data;
if (bitmask & mask)
data = fgPel;
else
data = BLACK_PIXEL;
DESTWRITEPIXEL(pbDest, data);
DESTNEXTPIXEL(pbDest);
mask = mask << 1;
});
return pbDest;
}
/**
* Decompress an RLE compressed bitmap.
*/
static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer,
UINT32 rowDelta, UINT32 width, UINT32 height)
{
const BYTE* pbSrc = pbSrcBuffer;
const BYTE* pbEnd;
const BYTE* pbDestEnd;
BYTE* pbDest = pbDestBuffer;
PIXEL temp;
PIXEL fgPel = WHITE_PIXEL;
BOOL fInsertFgPel = FALSE;
BOOL fFirstLine = TRUE;
BYTE bitmask;
PIXEL pixelA, pixelB;
UINT32 runLength;
UINT32 code;
UINT32 advance;
RLEEXTRA
if ((rowDelta == 0) || (rowDelta < width))
return FALSE;
if (!pbSrcBuffer || !pbDestBuffer)
return FALSE;
pbEnd = pbSrcBuffer + cbSrcBuffer;
pbDestEnd = pbDestBuffer + rowDelta * height;
while (pbSrc < pbEnd)
{
/* Watch out for the end of the first scanline. */
if (fFirstLine)
{
if ((UINT32)(pbDest - pbDestBuffer) >= rowDelta)
{
fFirstLine = FALSE;
fInsertFgPel = FALSE;
}
}
/*
Extract the compression order code ID from the compression
order header.
*/
code = ExtractCodeId(*pbSrc);
/* Handle Background Run Orders. */
if (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN)
{
runLength = ExtractRunLength(code, pbSrc, &advance);
pbSrc = pbSrc + advance;
if (fFirstLine)
{
if (fInsertFgPel)
{
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))
return FALSE;
DESTWRITEPIXEL(pbDest, fgPel);
DESTNEXTPIXEL(pbDest);
runLength = runLength - 1;
}
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))
return FALSE;
UNROLL(runLength, {
DESTWRITEPIXEL(pbDest, BLACK_PIXEL);
DESTNEXTPIXEL(pbDest);
});
}
else
{
if (fInsertFgPel)
{
DESTREADPIXEL(temp, pbDest - rowDelta);
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))
return FALSE;
DESTWRITEPIXEL(pbDest, temp ^ fgPel);
DESTNEXTPIXEL(pbDest);
runLength--;
}
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))
return FALSE;
UNROLL(runLength, {
DESTREADPIXEL(temp, pbDest - rowDelta);
DESTWRITEPIXEL(pbDest, temp);
DESTNEXTPIXEL(pbDest);
});
}
/* A follow-on background run order will need a foreground pel inserted. */
fInsertFgPel = TRUE;
continue;
}
/* For any of the other run-types a follow-on background run
order does not need a foreground pel inserted. */
fInsertFgPel = FALSE;
switch (code)
{
/* Handle Foreground Run Orders. */
case REGULAR_FG_RUN:
case MEGA_MEGA_FG_RUN:
case LITE_SET_FG_FG_RUN:
case MEGA_MEGA_SET_FG_RUN:
runLength = ExtractRunLength(code, pbSrc, &advance);
pbSrc = pbSrc + advance;
if (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN)
{
SRCREADPIXEL(fgPel, pbSrc);
SRCNEXTPIXEL(pbSrc);
}
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))
return FALSE;
if (fFirstLine)
{
UNROLL(runLength, {
DESTWRITEPIXEL(pbDest, fgPel);
DESTNEXTPIXEL(pbDest);
});
}
else
{
UNROLL(runLength, {
DESTREADPIXEL(temp, pbDest - rowDelta);
DESTWRITEPIXEL(pbDest, temp ^ fgPel);
DESTNEXTPIXEL(pbDest);
});
}
break;
/* Handle Dithered Run Orders. */
case LITE_DITHERED_RUN:
case MEGA_MEGA_DITHERED_RUN:
runLength = ExtractRunLength(code, pbSrc, &advance);
pbSrc = pbSrc + advance;
SRCREADPIXEL(pixelA, pbSrc);
SRCNEXTPIXEL(pbSrc);
SRCREADPIXEL(pixelB, pbSrc);
SRCNEXTPIXEL(pbSrc);
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2))
return FALSE;
UNROLL(runLength, {
DESTWRITEPIXEL(pbDest, pixelA);
DESTNEXTPIXEL(pbDest);
DESTWRITEPIXEL(pbDest, pixelB);
DESTNEXTPIXEL(pbDest);
});
break;
/* Handle Color Run Orders. */
case REGULAR_COLOR_RUN:
case MEGA_MEGA_COLOR_RUN:
runLength = ExtractRunLength(code, pbSrc, &advance);
pbSrc = pbSrc + advance;
SRCREADPIXEL(pixelA, pbSrc);
SRCNEXTPIXEL(pbSrc);
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))
return FALSE;
UNROLL(runLength, {
DESTWRITEPIXEL(pbDest, pixelA);
DESTNEXTPIXEL(pbDest);
});
break;
/* Handle Foreground/Background Image Orders. */
case REGULAR_FGBG_IMAGE:
case MEGA_MEGA_FGBG_IMAGE:
case LITE_SET_FG_FGBG_IMAGE:
case MEGA_MEGA_SET_FGBG_IMAGE:
runLength = ExtractRunLength(code, pbSrc, &advance);
pbSrc = pbSrc + advance;
if (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE)
{
SRCREADPIXEL(fgPel, pbSrc);
SRCNEXTPIXEL(pbSrc);
}
if (fFirstLine)
{
while (runLength > 8)
{
bitmask = *pbSrc;
pbSrc = pbSrc + 1;
pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8);
if (!pbDest)
return FALSE;
runLength = runLength - 8;
}
}
else
{
while (runLength > 8)
{
bitmask = *pbSrc;
pbSrc = pbSrc + 1;
pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8);
if (!pbDest)
return FALSE;
runLength = runLength - 8;
}
}
if (runLength > 0)
{
bitmask = *pbSrc;
pbSrc = pbSrc + 1;
if (fFirstLine)
{
pbDest =
WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength);
}
else
{
pbDest =
WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength);
}
if (!pbDest)
return FALSE;
}
break;
/* Handle Color Image Orders. */
case REGULAR_COLOR_IMAGE:
case MEGA_MEGA_COLOR_IMAGE:
runLength = ExtractRunLength(code, pbSrc, &advance);
pbSrc = pbSrc + advance;
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength))
return FALSE;
UNROLL(runLength, {
SRCREADPIXEL(temp, pbSrc);
SRCNEXTPIXEL(pbSrc);
DESTWRITEPIXEL(pbDest, temp);
DESTNEXTPIXEL(pbDest);
});
break;
/* Handle Special Order 1. */
case SPECIAL_FGBG_1:
pbSrc = pbSrc + 1;
if (fFirstLine)
{
pbDest =
WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8);
}
else
{
pbDest =
WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8);
}
if (!pbDest)
return FALSE;
break;
/* Handle Special Order 2. */
case SPECIAL_FGBG_2:
pbSrc = pbSrc + 1;
if (fFirstLine)
{
pbDest =
WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8);
}
else
{
pbDest =
WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8);
}
if (!pbDest)
return FALSE;
break;
/* Handle White Order. */
case SPECIAL_WHITE:
pbSrc = pbSrc + 1;
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))
return FALSE;
DESTWRITEPIXEL(pbDest, WHITE_PIXEL);
DESTNEXTPIXEL(pbDest);
break;
/* Handle Black Order. */
case SPECIAL_BLACK:
pbSrc = pbSrc + 1;
if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1))
return FALSE;
DESTWRITEPIXEL(pbDest, BLACK_PIXEL);
DESTNEXTPIXEL(pbDest);
break;
default:
return FALSE;
}
}
return TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4496_0 |
crossvul-cpp_data_good_3142_0 | /* GStreamer ASF/WMV/WMA demuxer
* Copyright (C) 1999 Erik Walthinsen <omega@cse.ogi.edu>
* Copyright (C) 2006-2009 Tim-Philipp Müller <tim centricular net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
/* TODO:
*
* - _loop():
* stop if at end of segment if != end of file, ie. demux->segment.stop
*
* - fix packet parsing:
* there's something wrong with timestamps for packets with keyframes,
* and durations too.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gstutils.h>
#include <gst/base/gstbytereader.h>
#include <gst/base/gsttypefindhelper.h>
#include <gst/riff/riff-media.h>
#include <gst/tag/tag.h>
#include <gst/gst-i18n-plugin.h>
#include <gst/video/video.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gstasfdemux.h"
#include "asfheaders.h"
#include "asfpacket.h"
static GstStaticPadTemplate gst_asf_demux_sink_template =
GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-ms-asf")
);
static GstStaticPadTemplate audio_src_template =
GST_STATIC_PAD_TEMPLATE ("audio_%u",
GST_PAD_SRC,
GST_PAD_SOMETIMES,
GST_STATIC_CAPS_ANY);
static GstStaticPadTemplate video_src_template =
GST_STATIC_PAD_TEMPLATE ("video_%u",
GST_PAD_SRC,
GST_PAD_SOMETIMES,
GST_STATIC_CAPS_ANY);
/* size of an ASF object header, ie. GUID (16 bytes) + object size (8 bytes) */
#define ASF_OBJECT_HEADER_SIZE (16+8)
/* FIXME: get rid of this */
/* abuse this GstFlowReturn enum for internal usage */
#define ASF_FLOW_NEED_MORE_DATA 99
#define gst_asf_get_flow_name(flow) \
(flow == ASF_FLOW_NEED_MORE_DATA) ? \
"need-more-data" : gst_flow_get_name (flow)
GST_DEBUG_CATEGORY (asfdemux_dbg);
static GstStateChangeReturn gst_asf_demux_change_state (GstElement * element,
GstStateChange transition);
static gboolean gst_asf_demux_element_send_event (GstElement * element,
GstEvent * event);
static gboolean gst_asf_demux_send_event_unlocked (GstASFDemux * demux,
GstEvent * event);
static gboolean gst_asf_demux_handle_src_query (GstPad * pad,
GstObject * parent, GstQuery * query);
static GstFlowReturn gst_asf_demux_chain (GstPad * pad, GstObject * parent,
GstBuffer * buf);
static gboolean gst_asf_demux_sink_event (GstPad * pad, GstObject * parent,
GstEvent * event);
static GstFlowReturn gst_asf_demux_process_object (GstASFDemux * demux,
guint8 ** p_data, guint64 * p_size);
static gboolean gst_asf_demux_activate (GstPad * sinkpad, GstObject * parent);
static gboolean gst_asf_demux_activate_mode (GstPad * sinkpad,
GstObject * parent, GstPadMode mode, gboolean active);
static void gst_asf_demux_loop (GstASFDemux * demux);
static void
gst_asf_demux_process_queued_extended_stream_objects (GstASFDemux * demux);
static gboolean gst_asf_demux_pull_headers (GstASFDemux * demux,
GstFlowReturn * pflow);
static GstFlowReturn gst_asf_demux_pull_indices (GstASFDemux * demux);
static void gst_asf_demux_reset_stream_state_after_discont (GstASFDemux * asf);
static gboolean
gst_asf_demux_parse_data_object_start (GstASFDemux * demux, guint8 * data);
static void gst_asf_demux_descramble_buffer (GstASFDemux * demux,
AsfStream * stream, GstBuffer ** p_buffer);
static void gst_asf_demux_activate_stream (GstASFDemux * demux,
AsfStream * stream);
static GstStructure *gst_asf_demux_get_metadata_for_stream (GstASFDemux * d,
guint stream_num);
static GstFlowReturn gst_asf_demux_push_complete_payloads (GstASFDemux * demux,
gboolean force);
#define gst_asf_demux_parent_class parent_class
G_DEFINE_TYPE (GstASFDemux, gst_asf_demux, GST_TYPE_ELEMENT);
static void
gst_asf_demux_class_init (GstASFDemuxClass * klass)
{
GstElementClass *gstelement_class;
gstelement_class = (GstElementClass *) klass;
gst_element_class_set_static_metadata (gstelement_class, "ASF Demuxer",
"Codec/Demuxer",
"Demultiplexes ASF Streams", "Owen Fraser-Green <owen@discobabe.net>");
gst_element_class_add_static_pad_template (gstelement_class,
&audio_src_template);
gst_element_class_add_static_pad_template (gstelement_class,
&video_src_template);
gst_element_class_add_static_pad_template (gstelement_class,
&gst_asf_demux_sink_template);
gstelement_class->change_state =
GST_DEBUG_FUNCPTR (gst_asf_demux_change_state);
gstelement_class->send_event =
GST_DEBUG_FUNCPTR (gst_asf_demux_element_send_event);
}
static void
gst_asf_demux_free_stream (GstASFDemux * demux, AsfStream * stream)
{
gst_caps_replace (&stream->caps, NULL);
if (stream->pending_tags) {
gst_tag_list_unref (stream->pending_tags);
stream->pending_tags = NULL;
}
if (stream->streamheader) {
gst_buffer_unref (stream->streamheader);
stream->streamheader = NULL;
}
if (stream->pad) {
if (stream->active) {
gst_element_remove_pad (GST_ELEMENT_CAST (demux), stream->pad);
gst_flow_combiner_remove_pad (demux->flowcombiner, stream->pad);
} else
gst_object_unref (stream->pad);
stream->pad = NULL;
}
if (stream->payloads) {
while (stream->payloads->len > 0) {
AsfPayload *payload;
guint last;
last = stream->payloads->len - 1;
payload = &g_array_index (stream->payloads, AsfPayload, last);
gst_buffer_replace (&payload->buf, NULL);
g_array_remove_index (stream->payloads, last);
}
g_array_free (stream->payloads, TRUE);
stream->payloads = NULL;
}
if (stream->payloads_rev) {
while (stream->payloads_rev->len > 0) {
AsfPayload *payload;
guint last;
last = stream->payloads_rev->len - 1;
payload = &g_array_index (stream->payloads_rev, AsfPayload, last);
gst_buffer_replace (&payload->buf, NULL);
g_array_remove_index (stream->payloads_rev, last);
}
g_array_free (stream->payloads_rev, TRUE);
stream->payloads_rev = NULL;
}
if (stream->ext_props.valid) {
g_free (stream->ext_props.payload_extensions);
stream->ext_props.payload_extensions = NULL;
}
}
static void
gst_asf_demux_reset (GstASFDemux * demux, gboolean chain_reset)
{
GST_LOG_OBJECT (demux, "resetting");
gst_segment_init (&demux->segment, GST_FORMAT_UNDEFINED);
demux->segment_running = FALSE;
if (demux->adapter && !chain_reset) {
gst_adapter_clear (demux->adapter);
g_object_unref (demux->adapter);
demux->adapter = NULL;
}
if (demux->taglist) {
gst_tag_list_unref (demux->taglist);
demux->taglist = NULL;
}
if (demux->metadata) {
gst_caps_unref (demux->metadata);
demux->metadata = NULL;
}
if (demux->global_metadata) {
gst_structure_free (demux->global_metadata);
demux->global_metadata = NULL;
}
if (demux->mut_ex_streams) {
g_slist_free (demux->mut_ex_streams);
demux->mut_ex_streams = NULL;
}
demux->state = GST_ASF_DEMUX_STATE_HEADER;
g_free (demux->objpath);
demux->objpath = NULL;
g_strfreev (demux->languages);
demux->languages = NULL;
demux->num_languages = 0;
g_slist_foreach (demux->ext_stream_props, (GFunc) gst_mini_object_unref,
NULL);
g_slist_free (demux->ext_stream_props);
demux->ext_stream_props = NULL;
while (demux->old_num_streams > 0) {
gst_asf_demux_free_stream (demux,
&demux->old_stream[demux->old_num_streams - 1]);
--demux->old_num_streams;
}
memset (demux->old_stream, 0, sizeof (demux->old_stream));
demux->old_num_streams = 0;
/* when resetting for a new chained asf, we don't want to remove the pads
* before adding the new ones */
if (chain_reset) {
memcpy (demux->old_stream, demux->stream, sizeof (demux->stream));
demux->old_num_streams = demux->num_streams;
demux->num_streams = 0;
}
while (demux->num_streams > 0) {
gst_asf_demux_free_stream (demux, &demux->stream[demux->num_streams - 1]);
--demux->num_streams;
}
memset (demux->stream, 0, sizeof (demux->stream));
if (!chain_reset) {
/* do not remove those for not adding pads with same name */
demux->num_audio_streams = 0;
demux->num_video_streams = 0;
demux->have_group_id = FALSE;
demux->group_id = G_MAXUINT;
}
demux->num_streams = 0;
demux->activated_streams = FALSE;
demux->first_ts = GST_CLOCK_TIME_NONE;
demux->segment_ts = GST_CLOCK_TIME_NONE;
demux->in_gap = 0;
if (!chain_reset)
gst_segment_init (&demux->in_segment, GST_FORMAT_UNDEFINED);
demux->state = GST_ASF_DEMUX_STATE_HEADER;
demux->seekable = FALSE;
demux->broadcast = FALSE;
demux->sidx_interval = 0;
demux->sidx_num_entries = 0;
g_free (demux->sidx_entries);
demux->sidx_entries = NULL;
demux->speed_packets = 1;
demux->asf_3D_mode = GST_ASF_3D_NONE;
if (chain_reset) {
GST_LOG_OBJECT (demux, "Restarting");
gst_segment_init (&demux->segment, GST_FORMAT_TIME);
demux->need_newsegment = TRUE;
demux->segment_seqnum = 0;
demux->segment_running = FALSE;
demux->keyunit_sync = FALSE;
demux->accurate = FALSE;
demux->metadata = gst_caps_new_empty ();
demux->global_metadata = gst_structure_new_empty ("metadata");
demux->data_size = 0;
demux->data_offset = 0;
demux->index_offset = 0;
} else {
demux->base_offset = 0;
}
g_slist_free (demux->other_streams);
demux->other_streams = NULL;
}
static void
gst_asf_demux_init (GstASFDemux * demux)
{
demux->sinkpad =
gst_pad_new_from_static_template (&gst_asf_demux_sink_template, "sink");
gst_pad_set_chain_function (demux->sinkpad,
GST_DEBUG_FUNCPTR (gst_asf_demux_chain));
gst_pad_set_event_function (demux->sinkpad,
GST_DEBUG_FUNCPTR (gst_asf_demux_sink_event));
gst_pad_set_activate_function (demux->sinkpad,
GST_DEBUG_FUNCPTR (gst_asf_demux_activate));
gst_pad_set_activatemode_function (demux->sinkpad,
GST_DEBUG_FUNCPTR (gst_asf_demux_activate_mode));
gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);
/* set initial state */
gst_asf_demux_reset (demux, FALSE);
}
static gboolean
gst_asf_demux_activate (GstPad * sinkpad, GstObject * parent)
{
GstQuery *query;
gboolean pull_mode;
query = gst_query_new_scheduling ();
if (!gst_pad_peer_query (sinkpad, query)) {
gst_query_unref (query);
goto activate_push;
}
pull_mode = gst_query_has_scheduling_mode_with_flags (query,
GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
gst_query_unref (query);
if (!pull_mode)
goto activate_push;
GST_DEBUG_OBJECT (sinkpad, "activating pull");
return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
activate_push:
{
GST_DEBUG_OBJECT (sinkpad, "activating push");
return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
}
}
static gboolean
gst_asf_demux_activate_mode (GstPad * sinkpad, GstObject * parent,
GstPadMode mode, gboolean active)
{
gboolean res;
GstASFDemux *demux;
demux = GST_ASF_DEMUX (parent);
switch (mode) {
case GST_PAD_MODE_PUSH:
demux->state = GST_ASF_DEMUX_STATE_HEADER;
demux->streaming = TRUE;
res = TRUE;
break;
case GST_PAD_MODE_PULL:
if (active) {
demux->state = GST_ASF_DEMUX_STATE_HEADER;
demux->streaming = FALSE;
res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_asf_demux_loop,
demux, NULL);
} else {
res = gst_pad_stop_task (sinkpad);
}
break;
default:
res = FALSE;
break;
}
return res;
}
static gboolean
gst_asf_demux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
{
GstASFDemux *demux;
gboolean ret = TRUE;
demux = GST_ASF_DEMUX (parent);
GST_LOG_OBJECT (demux, "handling %s event", GST_EVENT_TYPE_NAME (event));
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_SEGMENT:{
const GstSegment *segment;
gst_event_parse_segment (event, &segment);
if (segment->format == GST_FORMAT_BYTES) {
if (demux->packet_size && segment->start > demux->data_offset)
demux->packet = (segment->start - demux->data_offset) /
demux->packet_size;
else
demux->packet = 0;
} else if (segment->format == GST_FORMAT_TIME) {
/* do not know packet position, not really a problem */
demux->packet = -1;
} else {
GST_WARNING_OBJECT (demux, "unsupported newsegment format, ignoring");
gst_event_unref (event);
break;
}
/* record upstream segment for interpolation */
if (segment->format != demux->in_segment.format)
gst_segment_init (&demux->in_segment, GST_FORMAT_UNDEFINED);
gst_segment_copy_into (segment, &demux->in_segment);
/* in either case, clear some state and generate newsegment later on */
GST_OBJECT_LOCK (demux);
demux->segment_ts = GST_CLOCK_TIME_NONE;
demux->in_gap = GST_CLOCK_TIME_NONE;
demux->need_newsegment = TRUE;
demux->segment_seqnum = gst_event_get_seqnum (event);
gst_asf_demux_reset_stream_state_after_discont (demux);
/* if we seek back after reaching EOS, go back to packet reading state */
if (demux->data_offset > 0 && segment->start >= demux->data_offset
&& demux->state == GST_ASF_DEMUX_STATE_INDEX) {
demux->state = GST_ASF_DEMUX_STATE_DATA;
}
GST_OBJECT_UNLOCK (demux);
gst_event_unref (event);
break;
}
case GST_EVENT_EOS:{
GstFlowReturn flow;
if (demux->state == GST_ASF_DEMUX_STATE_HEADER) {
GST_ELEMENT_ERROR (demux, STREAM, DEMUX,
(_("This stream contains no data.")),
("got eos and didn't receive a complete header object"));
break;
}
flow = gst_asf_demux_push_complete_payloads (demux, TRUE);
if (!demux->activated_streams) {
/* If we still haven't got activated streams, the file is most likely corrupt */
GST_ELEMENT_ERROR (demux, STREAM, WRONG_TYPE,
(_("This stream contains no data.")),
("got eos and didn't receive a complete header object"));
break;
}
if (flow < GST_FLOW_EOS || flow == GST_FLOW_NOT_LINKED) {
GST_ELEMENT_FLOW_ERROR (demux, flow);
break;
}
GST_OBJECT_LOCK (demux);
gst_adapter_clear (demux->adapter);
GST_OBJECT_UNLOCK (demux);
gst_asf_demux_send_event_unlocked (demux, event);
break;
}
case GST_EVENT_FLUSH_STOP:
GST_OBJECT_LOCK (demux);
gst_asf_demux_reset_stream_state_after_discont (demux);
GST_OBJECT_UNLOCK (demux);
gst_asf_demux_send_event_unlocked (demux, event);
/* upon activation, latency is no longer introduced, e.g. after seek */
if (demux->activated_streams)
demux->latency = 0;
break;
default:
ret = gst_pad_event_default (pad, parent, event);
break;
}
return ret;
}
static gboolean
gst_asf_demux_seek_index_lookup (GstASFDemux * demux, guint * packet,
GstClockTime seek_time, GstClockTime * p_idx_time, guint * speed,
gboolean next, gboolean * eos)
{
GstClockTime idx_time;
guint idx;
if (eos)
*eos = FALSE;
if (G_UNLIKELY (demux->sidx_num_entries == 0 || demux->sidx_interval == 0))
return FALSE;
idx = (guint) ((seek_time + demux->preroll) / demux->sidx_interval);
if (next) {
/* if we want the next keyframe, we have to go forward till we find
a different packet number */
guint idx2;
if (idx >= demux->sidx_num_entries - 1) {
/* If we get here, we're asking for next keyframe after the last one. There isn't one. */
if (eos)
*eos = TRUE;
return FALSE;
}
for (idx2 = idx + 1; idx2 < demux->sidx_num_entries; ++idx2) {
if (demux->sidx_entries[idx].packet != demux->sidx_entries[idx2].packet) {
idx = idx2;
break;
}
}
}
if (G_UNLIKELY (idx >= demux->sidx_num_entries)) {
if (eos)
*eos = TRUE;
return FALSE;
}
*packet = demux->sidx_entries[idx].packet;
if (speed)
*speed = demux->sidx_entries[idx].count;
/* so we get closer to the actual time of the packet ... actually, let's not
* do this, since we throw away superfluous payloads before the seek position
* anyway; this way, our key unit seek 'snap resolution' is a bit better
* (ie. same as index resolution) */
/*
while (idx > 0 && demux->sidx_entries[idx-1] == demux->sidx_entries[idx])
--idx;
*/
idx_time = demux->sidx_interval * idx;
if (G_LIKELY (idx_time >= demux->preroll))
idx_time -= demux->preroll;
GST_DEBUG_OBJECT (demux, "%" GST_TIME_FORMAT " => packet %u at %"
GST_TIME_FORMAT, GST_TIME_ARGS (seek_time), *packet,
GST_TIME_ARGS (idx_time));
if (G_LIKELY (p_idx_time))
*p_idx_time = idx_time;
return TRUE;
}
static void
gst_asf_demux_reset_stream_state_after_discont (GstASFDemux * demux)
{
guint n;
gst_adapter_clear (demux->adapter);
GST_DEBUG_OBJECT (demux, "reset stream state");
gst_flow_combiner_reset (demux->flowcombiner);
for (n = 0; n < demux->num_streams; n++) {
demux->stream[n].discont = TRUE;
demux->stream[n].first_buffer = TRUE;
while (demux->stream[n].payloads->len > 0) {
AsfPayload *payload;
guint last;
last = demux->stream[n].payloads->len - 1;
payload = &g_array_index (demux->stream[n].payloads, AsfPayload, last);
gst_buffer_replace (&payload->buf, NULL);
g_array_remove_index (demux->stream[n].payloads, last);
}
}
}
static void
gst_asf_demux_mark_discont (GstASFDemux * demux)
{
guint n;
GST_DEBUG_OBJECT (demux, "Mark stream discont");
for (n = 0; n < demux->num_streams; n++)
demux->stream[n].discont = TRUE;
}
/* do a seek in push based mode */
static gboolean
gst_asf_demux_handle_seek_push (GstASFDemux * demux, GstEvent * event)
{
gdouble rate;
GstFormat format;
GstSeekFlags flags;
GstSeekType cur_type, stop_type;
gint64 cur, stop;
guint packet;
gboolean res;
GstEvent *byte_event;
gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
&stop_type, &stop);
stop_type = GST_SEEK_TYPE_NONE;
stop = -1;
GST_DEBUG_OBJECT (demux, "seeking to %" GST_TIME_FORMAT, GST_TIME_ARGS (cur));
/* determine packet, by index or by estimation */
if (!gst_asf_demux_seek_index_lookup (demux, &packet, cur, NULL, NULL, FALSE,
NULL)) {
packet =
(guint) gst_util_uint64_scale (demux->num_packets, cur,
demux->play_time);
}
if (packet > demux->num_packets) {
GST_DEBUG_OBJECT (demux, "could not determine packet to seek to, "
"seek aborted.");
return FALSE;
}
GST_DEBUG_OBJECT (demux, "seeking to packet %d", packet);
cur = demux->data_offset + ((guint64) packet * demux->packet_size);
GST_DEBUG_OBJECT (demux, "Pushing BYTE seek rate %g, "
"start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT, rate, cur, stop);
/* BYTE seek event */
byte_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, cur_type,
cur, stop_type, stop);
gst_event_set_seqnum (byte_event, gst_event_get_seqnum (event));
res = gst_pad_push_event (demux->sinkpad, byte_event);
return res;
}
static gboolean
gst_asf_demux_handle_seek_event (GstASFDemux * demux, GstEvent * event)
{
GstClockTime idx_time;
GstSegment segment;
GstSeekFlags flags;
GstSeekType cur_type, stop_type;
GstFormat format;
gboolean only_need_update;
gboolean after, before, next;
gboolean flush;
gdouble rate;
gint64 cur, stop;
gint64 seek_time;
guint packet, speed_count = 1;
gboolean eos;
guint32 seqnum;
GstEvent *fevent;
gint i;
gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
&stop_type, &stop);
if (G_UNLIKELY (format != GST_FORMAT_TIME)) {
GST_LOG_OBJECT (demux, "seeking is only supported in TIME format");
return FALSE;
}
/* upstream might handle TIME seek, e.g. mms or rtsp, or not, e.g. http,
* so first try to let it handle the seek event. */
if (gst_pad_push_event (demux->sinkpad, gst_event_ref (event)))
return TRUE;
if (G_UNLIKELY (demux->seekable == FALSE || demux->packet_size == 0 ||
demux->num_packets == 0 || demux->play_time == 0)) {
GST_LOG_OBJECT (demux, "stream is not seekable");
return FALSE;
}
if (G_UNLIKELY (!demux->activated_streams)) {
GST_LOG_OBJECT (demux, "streams not yet activated, ignoring seek");
return FALSE;
}
if (G_UNLIKELY (rate <= 0.0)) {
GST_LOG_OBJECT (demux, "backward playback");
demux->seek_to_cur_pos = TRUE;
for (i = 0; i < demux->num_streams; i++) {
demux->stream[i].reverse_kf_ready = FALSE;
}
}
seqnum = gst_event_get_seqnum (event);
flush = ((flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH);
demux->accurate =
((flags & GST_SEEK_FLAG_ACCURATE) == GST_SEEK_FLAG_ACCURATE);
demux->keyunit_sync =
((flags & GST_SEEK_FLAG_KEY_UNIT) == GST_SEEK_FLAG_KEY_UNIT);
after = ((flags & GST_SEEK_FLAG_SNAP_AFTER) == GST_SEEK_FLAG_SNAP_AFTER);
before = ((flags & GST_SEEK_FLAG_SNAP_BEFORE) == GST_SEEK_FLAG_SNAP_BEFORE);
next = after && !before;
if (G_UNLIKELY (demux->streaming)) {
/* support it safely needs more segment handling, e.g. closing etc */
if (!flush) {
GST_LOG_OBJECT (demux, "streaming; non-flushing seek not supported");
return FALSE;
}
/* we can (re)construct the start later on, but not the end */
if (stop_type != GST_SEEK_TYPE_NONE &&
(stop_type != GST_SEEK_TYPE_SET || GST_CLOCK_TIME_IS_VALID (stop))) {
GST_LOG_OBJECT (demux, "streaming; end position must be NONE");
return FALSE;
}
return gst_asf_demux_handle_seek_push (demux, event);
}
/* unlock the streaming thread */
if (G_LIKELY (flush)) {
fevent = gst_event_new_flush_start ();
gst_event_set_seqnum (fevent, seqnum);
gst_pad_push_event (demux->sinkpad, gst_event_ref (fevent));
gst_asf_demux_send_event_unlocked (demux, fevent);
} else {
gst_pad_pause_task (demux->sinkpad);
}
/* grab the stream lock so that streaming cannot continue, for
* non flushing seeks when the element is in PAUSED this could block
* forever */
GST_PAD_STREAM_LOCK (demux->sinkpad);
/* we now can stop flushing, since we have the stream lock now */
fevent = gst_event_new_flush_stop (TRUE);
gst_event_set_seqnum (fevent, seqnum);
gst_pad_push_event (demux->sinkpad, gst_event_ref (fevent));
if (G_LIKELY (flush))
gst_asf_demux_send_event_unlocked (demux, fevent);
else
gst_event_unref (fevent);
/* operating on copy of segment until we know the seek worked */
segment = demux->segment;
if (G_UNLIKELY (demux->segment_running && !flush)) {
GstSegment newsegment;
GstEvent *newseg;
/* create the segment event to close the current segment */
gst_segment_copy_into (&segment, &newsegment);
newseg = gst_event_new_segment (&newsegment);
gst_event_set_seqnum (newseg, seqnum);
gst_asf_demux_send_event_unlocked (demux, newseg);
}
gst_segment_do_seek (&segment, rate, format, flags, cur_type,
cur, stop_type, stop, &only_need_update);
GST_DEBUG_OBJECT (demux, "seeking to time %" GST_TIME_FORMAT ", segment: "
"%" GST_SEGMENT_FORMAT, GST_TIME_ARGS (segment.start), &segment);
if (cur_type != GST_SEEK_TYPE_SET)
seek_time = segment.start;
else
seek_time = cur;
/* FIXME: should check the KEY_UNIT flag; need to adjust position to
* real start of data and segment_start to indexed time for key unit seek*/
if (G_UNLIKELY (!gst_asf_demux_seek_index_lookup (demux, &packet, seek_time,
&idx_time, &speed_count, next, &eos))) {
gint64 offset;
if (eos) {
demux->packet = demux->num_packets;
goto skip;
}
/* First try to query our source to see if it can convert for us. This is
the case when our source is an mms stream, notice that in this case
gstmms will do a time based seek to get the byte offset, this is not a
problem as the seek to this offset needs to happen anway. */
if (gst_pad_peer_query_convert (demux->sinkpad, GST_FORMAT_TIME, seek_time,
GST_FORMAT_BYTES, &offset)) {
packet = (offset - demux->data_offset) / demux->packet_size;
GST_LOG_OBJECT (demux, "convert %" GST_TIME_FORMAT
" to bytes query result: %" G_GINT64_FORMAT ", data_ofset: %"
G_GINT64_FORMAT ", packet_size: %u," " resulting packet: %u\n",
GST_TIME_ARGS (seek_time), offset, demux->data_offset,
demux->packet_size, packet);
} else {
/* FIXME: For streams containing video, seek to an earlier position in
* the hope of hitting a keyframe and let the sinks throw away the stuff
* before the segment start. For audio-only this is unnecessary as every
* frame is 'key'. */
if (flush && (demux->accurate || (demux->keyunit_sync && !next))
&& demux->num_video_streams > 0) {
seek_time -= 5 * GST_SECOND;
if (seek_time < 0)
seek_time = 0;
}
packet = (guint) gst_util_uint64_scale (demux->num_packets,
seek_time, demux->play_time);
if (packet > demux->num_packets)
packet = demux->num_packets;
}
} else {
if (G_LIKELY (demux->keyunit_sync && !demux->accurate)) {
GST_DEBUG_OBJECT (demux, "key unit seek, adjust seek_time = %"
GST_TIME_FORMAT " to index_time = %" GST_TIME_FORMAT,
GST_TIME_ARGS (seek_time), GST_TIME_ARGS (idx_time));
segment.start = idx_time;
segment.position = idx_time;
segment.time = idx_time;
}
}
GST_DEBUG_OBJECT (demux, "seeking to packet %u (%d)", packet, speed_count);
GST_OBJECT_LOCK (demux);
demux->segment = segment;
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)) {
demux->packet = (gint64) gst_util_uint64_scale (demux->num_packets,
stop, demux->play_time);
} else {
demux->packet = packet;
}
demux->need_newsegment = TRUE;
demux->segment_seqnum = seqnum;
demux->speed_packets =
GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment) ? 1 : speed_count;
gst_asf_demux_reset_stream_state_after_discont (demux);
GST_OBJECT_UNLOCK (demux);
skip:
/* restart our task since it might have been stopped when we did the flush */
gst_pad_start_task (demux->sinkpad, (GstTaskFunction) gst_asf_demux_loop,
demux, NULL);
/* streaming can continue now */
GST_PAD_STREAM_UNLOCK (demux->sinkpad);
return TRUE;
}
static gboolean
gst_asf_demux_handle_src_event (GstPad * pad, GstObject * parent,
GstEvent * event)
{
GstASFDemux *demux;
gboolean ret;
demux = GST_ASF_DEMUX (parent);
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_SEEK:
GST_LOG_OBJECT (pad, "seek event");
ret = gst_asf_demux_handle_seek_event (demux, event);
gst_event_unref (event);
break;
case GST_EVENT_QOS:
case GST_EVENT_NAVIGATION:
/* just drop these two silently */
gst_event_unref (event);
ret = FALSE;
break;
default:
GST_LOG_OBJECT (pad, "%s event", GST_EVENT_TYPE_NAME (event));
ret = gst_pad_event_default (pad, parent, event);
break;
}
return ret;
}
static inline guint32
gst_asf_demux_identify_guid (const ASFGuidHash * guids, ASFGuid * guid)
{
guint32 ret;
ret = gst_asf_identify_guid (guids, guid);
GST_LOG ("%s 0x%08x-0x%08x-0x%08x-0x%08x",
gst_asf_get_guid_nick (guids, ret),
guid->v1, guid->v2, guid->v3, guid->v4);
return ret;
}
typedef struct
{
AsfObjectID id;
guint64 size;
} AsfObject;
/* Peek for an object.
*
* Returns FALSE is the object is corrupted (such as the reported
* object size being greater than 2**32bits.
*/
static gboolean
asf_demux_peek_object (GstASFDemux * demux, const guint8 * data,
guint data_len, AsfObject * object, gboolean expect)
{
ASFGuid guid;
/* Callers should have made sure that data_len is big enough */
g_assert (data_len >= ASF_OBJECT_HEADER_SIZE);
if (data_len < ASF_OBJECT_HEADER_SIZE)
return FALSE;
guid.v1 = GST_READ_UINT32_LE (data + 0);
guid.v2 = GST_READ_UINT32_LE (data + 4);
guid.v3 = GST_READ_UINT32_LE (data + 8);
guid.v4 = GST_READ_UINT32_LE (data + 12);
/* FIXME: make asf_demux_identify_object_guid() */
object->id = gst_asf_demux_identify_guid (asf_object_guids, &guid);
if (object->id == ASF_OBJ_UNDEFINED && expect) {
GST_WARNING_OBJECT (demux, "Unknown object %08x-%08x-%08x-%08x",
guid.v1, guid.v2, guid.v3, guid.v4);
}
object->size = GST_READ_UINT64_LE (data + 16);
if (object->id != ASF_OBJ_DATA && object->size >= G_MAXUINT) {
GST_WARNING_OBJECT (demux,
"ASF Object size corrupted (greater than 32bit)");
return FALSE;
}
return TRUE;
}
static void
gst_asf_demux_release_old_pads (GstASFDemux * demux)
{
GST_DEBUG_OBJECT (demux, "Releasing old pads");
while (demux->old_num_streams > 0) {
gst_pad_push_event (demux->old_stream[demux->old_num_streams - 1].pad,
gst_event_new_eos ());
gst_asf_demux_free_stream (demux,
&demux->old_stream[demux->old_num_streams - 1]);
--demux->old_num_streams;
}
memset (demux->old_stream, 0, sizeof (demux->old_stream));
demux->old_num_streams = 0;
}
static GstFlowReturn
gst_asf_demux_chain_headers (GstASFDemux * demux)
{
AsfObject obj;
guint8 *header_data, *data = NULL;
const guint8 *cdata = NULL;
guint64 header_size;
GstFlowReturn flow = GST_FLOW_OK;
cdata = (guint8 *) gst_adapter_map (demux->adapter, ASF_OBJECT_HEADER_SIZE);
if (cdata == NULL)
goto need_more_data;
if (!asf_demux_peek_object (demux, cdata, ASF_OBJECT_HEADER_SIZE, &obj, TRUE))
goto parse_failed;
if (obj.id != ASF_OBJ_HEADER)
goto wrong_type;
GST_LOG_OBJECT (demux, "header size = %u", (guint) obj.size);
/* + 50 for non-packet data at beginning of ASF_OBJ_DATA */
if (gst_adapter_available (demux->adapter) < obj.size + 50)
goto need_more_data;
data = gst_adapter_take (demux->adapter, obj.size + 50);
header_data = data;
header_size = obj.size;
flow = gst_asf_demux_process_object (demux, &header_data, &header_size);
if (flow != GST_FLOW_OK)
goto parse_failed;
/* calculate where the packet data starts */
demux->data_offset = obj.size + 50;
/* now parse the beginning of the ASF_OBJ_DATA object */
if (!gst_asf_demux_parse_data_object_start (demux, data + obj.size))
goto wrong_type;
if (demux->num_streams == 0)
goto no_streams;
g_free (data);
return GST_FLOW_OK;
/* NON-FATAL */
need_more_data:
{
GST_LOG_OBJECT (demux, "not enough data in adapter yet");
return GST_FLOW_OK;
}
/* ERRORS */
wrong_type:
{
GST_ELEMENT_ERROR (demux, STREAM, WRONG_TYPE, (NULL),
("This doesn't seem to be an ASF file"));
g_free (data);
return GST_FLOW_ERROR;
}
no_streams:
parse_failed:
{
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("header parsing failed, or no streams found, flow = %s",
gst_flow_get_name (flow)));
g_free (data);
return GST_FLOW_ERROR;
}
}
static gboolean
gst_asf_demux_pull_data (GstASFDemux * demux, guint64 offset, guint size,
GstBuffer ** p_buf, GstFlowReturn * p_flow)
{
gsize buffer_size;
GstFlowReturn flow;
GST_LOG_OBJECT (demux, "pulling buffer at %" G_GUINT64_FORMAT "+%u",
offset, size);
flow = gst_pad_pull_range (demux->sinkpad, offset, size, p_buf);
if (G_LIKELY (p_flow))
*p_flow = flow;
if (G_UNLIKELY (flow != GST_FLOW_OK)) {
GST_DEBUG_OBJECT (demux, "flow %s pulling buffer at %" G_GUINT64_FORMAT
"+%u", gst_flow_get_name (flow), offset, size);
*p_buf = NULL;
return FALSE;
}
g_assert (*p_buf != NULL);
buffer_size = gst_buffer_get_size (*p_buf);
if (G_UNLIKELY (buffer_size < size)) {
GST_DEBUG_OBJECT (demux, "short read pulling buffer at %" G_GUINT64_FORMAT
"+%u (got only %" G_GSIZE_FORMAT " bytes)", offset, size, buffer_size);
gst_buffer_unref (*p_buf);
if (G_LIKELY (p_flow))
*p_flow = GST_FLOW_EOS;
*p_buf = NULL;
return FALSE;
}
return TRUE;
}
static GstFlowReturn
gst_asf_demux_pull_indices (GstASFDemux * demux)
{
GstBuffer *buf = NULL;
guint64 offset;
guint num_read = 0;
GstFlowReturn ret = GST_FLOW_OK;
offset = demux->index_offset;
if (G_UNLIKELY (offset == 0)) {
GST_DEBUG_OBJECT (demux, "can't read indices, don't know index offset");
/* non-fatal */
return GST_FLOW_OK;
}
while (gst_asf_demux_pull_data (demux, offset, 16 + 8, &buf, NULL)) {
AsfObject obj;
GstMapInfo map;
guint8 *bufdata;
guint64 obj_size;
gst_buffer_map (buf, &map, GST_MAP_READ);
g_assert (map.size >= 16 + 8);
if (!asf_demux_peek_object (demux, map.data, 16 + 8, &obj, TRUE)) {
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
ret = GST_FLOW_ERROR;
break;
}
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
/* check for sanity */
if (G_UNLIKELY (obj.size > (5 * 1024 * 1024))) {
GST_DEBUG_OBJECT (demux, "implausible index object size, bailing out");
break;
}
if (G_UNLIKELY (!gst_asf_demux_pull_data (demux, offset, obj.size, &buf,
NULL)))
break;
GST_LOG_OBJECT (demux, "index object at offset 0x%" G_GINT64_MODIFIER "X"
", size %u", offset, (guint) obj.size);
offset += obj.size; /* increase before _process_object changes it */
gst_buffer_map (buf, &map, GST_MAP_READ);
g_assert (map.size >= obj.size);
bufdata = (guint8 *) map.data;
obj_size = obj.size;
ret = gst_asf_demux_process_object (demux, &bufdata, &obj_size);
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
if (G_UNLIKELY (ret != GST_FLOW_OK))
break;
++num_read;
}
GST_DEBUG_OBJECT (demux, "read %u index objects", num_read);
return ret;
}
static gboolean
gst_asf_demux_parse_data_object_start (GstASFDemux * demux, guint8 * data)
{
AsfObject obj;
if (!asf_demux_peek_object (demux, data, 50, &obj, TRUE)) {
GST_WARNING_OBJECT (demux, "Corrupted data");
return FALSE;
}
if (obj.id != ASF_OBJ_DATA) {
GST_WARNING_OBJECT (demux, "headers not followed by a DATA object");
return FALSE;
}
demux->state = GST_ASF_DEMUX_STATE_DATA;
if (!demux->broadcast && obj.size > 50) {
demux->data_size = obj.size - 50;
/* CHECKME: for at least one file this is off by +158 bytes?! */
demux->index_offset = demux->data_offset + demux->data_size;
} else {
demux->data_size = 0;
demux->index_offset = 0;
}
demux->packet = 0;
if (!demux->broadcast) {
/* skip object header (24 bytes) and file GUID (16 bytes) */
demux->num_packets = GST_READ_UINT64_LE (data + (16 + 8) + 16);
} else {
demux->num_packets = 0;
}
if (demux->num_packets == 0)
demux->seekable = FALSE;
/* fallback in the unlikely case that headers are inconsistent, can't hurt */
if (demux->data_size == 0 && demux->num_packets > 0) {
demux->data_size = demux->num_packets * demux->packet_size;
demux->index_offset = demux->data_offset + demux->data_size;
}
/* process pending stream objects and create pads for those */
gst_asf_demux_process_queued_extended_stream_objects (demux);
GST_INFO_OBJECT (demux, "Stream has %" G_GUINT64_FORMAT " packets, "
"data_offset=%" G_GINT64_FORMAT ", data_size=%" G_GINT64_FORMAT
", index_offset=%" G_GUINT64_FORMAT, demux->num_packets,
demux->data_offset, demux->data_size, demux->index_offset);
return TRUE;
}
static gboolean
gst_asf_demux_pull_headers (GstASFDemux * demux, GstFlowReturn * pflow)
{
GstFlowReturn flow = GST_FLOW_OK;
AsfObject obj;
GstBuffer *buf = NULL;
guint64 size;
GstMapInfo map;
guint8 *bufdata;
GST_LOG_OBJECT (demux, "reading headers");
/* pull HEADER object header, so we know its size */
if (!gst_asf_demux_pull_data (demux, demux->base_offset, 16 + 8, &buf, &flow))
goto read_failed;
gst_buffer_map (buf, &map, GST_MAP_READ);
g_assert (map.size >= 16 + 8);
if (!asf_demux_peek_object (demux, map.data, 16 + 8, &obj, TRUE)) {
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
flow = GST_FLOW_ERROR;
goto read_failed;
}
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
if (obj.id != ASF_OBJ_HEADER)
goto wrong_type;
GST_LOG_OBJECT (demux, "header size = %" G_GUINT64_FORMAT, obj.size);
/* pull HEADER object */
if (!gst_asf_demux_pull_data (demux, demux->base_offset, obj.size, &buf,
&flow))
goto read_failed;
size = obj.size; /* don't want obj.size changed */
gst_buffer_map (buf, &map, GST_MAP_READ);
g_assert (map.size >= size);
bufdata = (guint8 *) map.data;
flow = gst_asf_demux_process_object (demux, &bufdata, &size);
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
if (flow != GST_FLOW_OK) {
GST_WARNING_OBJECT (demux, "process_object: %s", gst_flow_get_name (flow));
goto parse_failed;
}
/* calculate where the packet data starts */
demux->data_offset = demux->base_offset + obj.size + 50;
/* now pull beginning of DATA object before packet data */
if (!gst_asf_demux_pull_data (demux, demux->base_offset + obj.size, 50, &buf,
&flow))
goto read_failed;
gst_buffer_map (buf, &map, GST_MAP_READ);
g_assert (map.size >= size);
bufdata = (guint8 *) map.data;
if (!gst_asf_demux_parse_data_object_start (demux, bufdata))
goto wrong_type;
if (demux->num_streams == 0)
goto no_streams;
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
return TRUE;
/* ERRORS */
wrong_type:
{
if (buf != NULL) {
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
}
GST_ELEMENT_ERROR (demux, STREAM, WRONG_TYPE, (NULL),
("This doesn't seem to be an ASF file"));
*pflow = GST_FLOW_ERROR;
return FALSE;
}
no_streams:
flow = GST_FLOW_ERROR;
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("header parsing failed, or no streams found, flow = %s",
gst_flow_get_name (flow)));
read_failed:
parse_failed:
{
if (buf)
gst_buffer_unmap (buf, &map);
gst_buffer_replace (&buf, NULL);
if (flow == ASF_FLOW_NEED_MORE_DATA)
flow = GST_FLOW_ERROR;
*pflow = flow;
return FALSE;
}
}
static gboolean
all_streams_prerolled (GstASFDemux * demux)
{
GstClockTime preroll_time;
guint i, num_no_data = 0;
/* Allow at least 500ms of preroll_time */
preroll_time = MAX (demux->preroll, 500 * GST_MSECOND);
/* returns TRUE as long as there isn't a stream which (a) has data queued
* and (b) the timestamp of last piece of data queued is < demux->preroll
* AND there is at least one other stream with data queued */
for (i = 0; i < demux->num_streams; ++i) {
AsfPayload *last_payload = NULL;
AsfStream *stream;
gint last_idx;
stream = &demux->stream[i];
if (G_UNLIKELY (stream->payloads->len == 0)) {
++num_no_data;
GST_LOG_OBJECT (stream->pad, "no data queued");
continue;
}
/* find last payload with timestamp */
for (last_idx = stream->payloads->len - 1;
last_idx >= 0 && (last_payload == NULL
|| !GST_CLOCK_TIME_IS_VALID (last_payload->ts)); --last_idx) {
last_payload = &g_array_index (stream->payloads, AsfPayload, last_idx);
}
GST_LOG_OBJECT (stream->pad, "checking if %" GST_TIME_FORMAT " > %"
GST_TIME_FORMAT, GST_TIME_ARGS (last_payload->ts),
GST_TIME_ARGS (preroll_time));
if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (last_payload->ts)
|| last_payload->ts <= preroll_time)) {
GST_LOG_OBJECT (stream->pad, "not beyond preroll point yet");
return FALSE;
}
}
if (G_UNLIKELY (num_no_data > 0))
return FALSE;
return TRUE;
}
#if 0
static gboolean
gst_asf_demux_have_mutually_exclusive_active_stream (GstASFDemux * demux,
AsfStream * stream)
{
GSList *l;
for (l = demux->mut_ex_streams; l != NULL; l = l->next) {
guint8 *mes;
/* check for each mutual exclusion group whether it affects this stream */
for (mes = (guint8 *) l->data; mes != NULL && *mes != 0xff; ++mes) {
if (*mes == stream->id) {
/* we are in this group; let's check if we've already activated streams
* that are in the same group (and hence mutually exclusive to this
* one) */
for (mes = (guint8 *) l->data; mes != NULL && *mes != 0xff; ++mes) {
guint i;
for (i = 0; i < demux->num_streams; ++i) {
if (demux->stream[i].id == *mes && demux->stream[i].active) {
GST_LOG_OBJECT (demux, "stream with ID %d is mutually exclusive "
"to already active stream with ID %d", stream->id,
demux->stream[i].id);
return TRUE;
}
}
}
/* we can only be in this group once, let's break out and move on to
* the next mutual exclusion group */
break;
}
}
}
return FALSE;
}
#endif
static void
gst_asf_demux_check_segment_ts (GstASFDemux * demux, GstClockTime payload_ts)
{
/* remember the first queued timestamp for the segment */
if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (demux->segment_ts) &&
GST_CLOCK_TIME_IS_VALID (demux->first_ts))) {
GST_DEBUG_OBJECT (demux, "segment ts: %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->first_ts));
demux->segment_ts = payload_ts;
/* always note, but only determines segment when streaming */
if (demux->streaming)
gst_segment_do_seek (&demux->segment, demux->in_segment.rate,
GST_FORMAT_TIME, (GstSeekFlags) demux->segment.flags,
GST_SEEK_TYPE_SET, demux->segment_ts, GST_SEEK_TYPE_NONE, 0, NULL);
}
}
static gboolean
gst_asf_demux_check_first_ts (GstASFDemux * demux, gboolean force)
{
if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (demux->first_ts))) {
GstClockTime first_ts = GST_CLOCK_TIME_NONE;
int i;
/* go trhough each stream, find smallest timestamp */
for (i = 0; i < demux->num_streams; ++i) {
AsfStream *stream;
int j;
GstClockTime stream_min_ts = GST_CLOCK_TIME_NONE;
GstClockTime stream_min_ts2 = GST_CLOCK_TIME_NONE; /* second smallest timestamp */
stream = &demux->stream[i];
for (j = 0; j < stream->payloads->len; ++j) {
AsfPayload *payload = &g_array_index (stream->payloads, AsfPayload, j);
if (GST_CLOCK_TIME_IS_VALID (payload->ts) &&
(!GST_CLOCK_TIME_IS_VALID (stream_min_ts)
|| stream_min_ts > payload->ts)) {
stream_min_ts = payload->ts;
}
if (GST_CLOCK_TIME_IS_VALID (payload->ts) &&
payload->ts > stream_min_ts &&
(!GST_CLOCK_TIME_IS_VALID (stream_min_ts2)
|| stream_min_ts2 > payload->ts)) {
stream_min_ts2 = payload->ts;
}
}
/* there are some DVR ms files where first packet has TS of 0 (instead of -1) while subsequent packets have
regular (singificantly larger) timestamps. If we don't deal with it, we may end up with huge gap in timestamps
which makes playback stuck. The 0 timestamp may also be valid though, if the second packet timestamp continues
from it. I havent found a better way to distinguish between these two, except to set an arbitrary boundary
and disregard the first 0 timestamp if the second timestamp is bigger than the boundary) */
if (stream_min_ts == 0 && stream_min_ts2 == GST_CLOCK_TIME_NONE && !force) /* still waiting for the second timestamp */
return FALSE;
if (stream_min_ts == 0 && stream_min_ts2 > GST_SECOND) /* first timestamp is 0 and second is significantly larger, disregard the 0 */
stream_min_ts = stream_min_ts2;
/* if we don't have timestamp for this stream, wait for more data */
if (!GST_CLOCK_TIME_IS_VALID (stream_min_ts) && !force)
return FALSE;
if (GST_CLOCK_TIME_IS_VALID (stream_min_ts) &&
(!GST_CLOCK_TIME_IS_VALID (first_ts) || first_ts > stream_min_ts))
first_ts = stream_min_ts;
}
if (!GST_CLOCK_TIME_IS_VALID (first_ts)) /* can happen with force = TRUE */
first_ts = 0;
demux->first_ts = first_ts;
/* update packets queued before we knew first timestamp */
for (i = 0; i < demux->num_streams; ++i) {
AsfStream *stream;
int j;
stream = &demux->stream[i];
for (j = 0; j < stream->payloads->len; ++j) {
AsfPayload *payload = &g_array_index (stream->payloads, AsfPayload, j);
if (GST_CLOCK_TIME_IS_VALID (payload->ts)) {
if (payload->ts > first_ts)
payload->ts -= first_ts;
else
payload->ts = 0;
}
}
}
}
gst_asf_demux_check_segment_ts (demux, 0);
return TRUE;
}
static gboolean
gst_asf_demux_update_caps_from_payload (GstASFDemux * demux, AsfStream * stream)
{
/* try to determine whether the stream is AC-3 or MPEG; In dvr-ms the codecTag is unreliable
and often set wrong, inspecting the data is the only way that seem to be working */
GstTypeFindProbability prob = GST_TYPE_FIND_NONE;
GstCaps *caps = NULL;
int i;
GstAdapter *adapter = gst_adapter_new ();
for (i = 0; i < stream->payloads->len && prob < GST_TYPE_FIND_LIKELY; ++i) {
const guint8 *data;
AsfPayload *payload;
int len;
payload = &g_array_index (stream->payloads, AsfPayload, i);
gst_adapter_push (adapter, gst_buffer_ref (payload->buf));
len = gst_adapter_available (adapter);
data = gst_adapter_map (adapter, len);
again:
#define MIN_LENGTH 128
/* look for the sync points */
while (TRUE) {
if (len < MIN_LENGTH || /* give typefind something to work on */
(data[0] == 0x0b && data[1] == 0x77) || /* AC-3 sync point */
(data[0] == 0xFF && ((data[1] & 0xF0) >> 4) == 0xF)) /* MPEG sync point */
break;
++data;
--len;
}
gst_caps_take (&caps, gst_type_find_helper_for_data (GST_OBJECT (demux),
data, len, &prob));
if (prob < GST_TYPE_FIND_LIKELY) {
++data;
--len;
if (len > MIN_LENGTH)
/* this wasn't it, look for another sync point */
goto again;
}
gst_adapter_unmap (adapter);
}
gst_object_unref (adapter);
if (caps) {
gst_caps_take (&stream->caps, caps);
return TRUE;
} else {
return FALSE;
}
}
static gboolean
gst_asf_demux_check_activate_streams (GstASFDemux * demux, gboolean force)
{
guint i, actual_streams = 0;
if (demux->activated_streams)
return TRUE;
if (G_UNLIKELY (!gst_asf_demux_check_first_ts (demux, force)))
return FALSE;
if (!all_streams_prerolled (demux) && !force) {
GST_DEBUG_OBJECT (demux, "not all streams with data beyond preroll yet");
return FALSE;
}
for (i = 0; i < demux->num_streams; ++i) {
AsfStream *stream = &demux->stream[i];
if (stream->payloads->len > 0) {
if (stream->inspect_payload && /* dvr-ms required payload inspection */
!stream->active && /* do not inspect active streams (caps were already set) */
!gst_asf_demux_update_caps_from_payload (demux, stream) && /* failed to determine caps */
stream->payloads->len < 20) { /* if we couldn't determine the caps from 20 packets then just give up and use whatever was in codecTag */
/* try to gather some more data */
return FALSE;
}
/* we don't check mutual exclusion stuff here; either we have data for
* a stream, then we active it, or we don't, then we'll ignore it */
GST_LOG_OBJECT (stream->pad, "is prerolled - activate!");
gst_asf_demux_activate_stream (demux, stream);
actual_streams += 1;
} else {
GST_LOG_OBJECT (stream->pad, "no data, ignoring stream");
}
}
if (actual_streams == 0) {
/* We don't have any streams activated ! */
GST_ERROR_OBJECT (demux, "No streams activated!");
return FALSE;
}
gst_asf_demux_release_old_pads (demux);
demux->activated_streams = TRUE;
GST_LOG_OBJECT (demux, "signalling no more pads");
gst_element_no_more_pads (GST_ELEMENT (demux));
return TRUE;
}
/* returns the stream that has a complete payload with the lowest timestamp
* queued, or NULL (we push things by timestamp because during the internal
* prerolling we might accumulate more data then the external queues can take,
* so we'd lock up if we pushed all accumulated data for stream N in one go) */
static AsfStream *
gst_asf_demux_find_stream_with_complete_payload (GstASFDemux * demux)
{
AsfPayload *best_payload = NULL;
AsfStream *best_stream = NULL;
guint i;
for (i = 0; i < demux->num_streams; ++i) {
AsfStream *stream;
int j;
stream = &demux->stream[i];
/* Don't push any data until we have at least one payload that falls within
* the current segment. This way we can remove out-of-segment payloads that
* don't need to be decoded after a seek, sending only data from the
* keyframe directly before our segment start */
if (stream->payloads->len > 0) {
AsfPayload *payload = NULL;
gint last_idx;
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)) {
/* Reverse playback */
if (stream->is_video) {
/* We have to push payloads from KF to the first frame we accumulated (reverse order) */
if (stream->reverse_kf_ready) {
payload =
&g_array_index (stream->payloads, AsfPayload, stream->kf_pos);
if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (payload->ts))) {
/* TODO : remove payload from the list? */
continue;
}
} else {
continue;
}
} else {
/* find first complete payload with timestamp */
for (j = stream->payloads->len - 1;
j >= 0 && (payload == NULL
|| !GST_CLOCK_TIME_IS_VALID (payload->ts)); --j) {
payload = &g_array_index (stream->payloads, AsfPayload, j);
}
/* If there's a complete payload queued for this stream */
if (!gst_asf_payload_is_complete (payload))
continue;
}
} else {
/* find last payload with timestamp */
for (last_idx = stream->payloads->len - 1;
last_idx >= 0 && (payload == NULL
|| !GST_CLOCK_TIME_IS_VALID (payload->ts)); --last_idx) {
payload = &g_array_index (stream->payloads, AsfPayload, last_idx);
}
/* if this is first payload after seek we might need to update the segment */
if (GST_CLOCK_TIME_IS_VALID (payload->ts))
gst_asf_demux_check_segment_ts (demux, payload->ts);
if (G_UNLIKELY (GST_CLOCK_TIME_IS_VALID (payload->ts) &&
(payload->ts < demux->segment.start))) {
if (G_UNLIKELY ((!demux->keyunit_sync) && (!demux->accurate)
&& payload->keyframe)) {
GST_DEBUG_OBJECT (stream->pad,
"Found keyframe, updating segment start to %" GST_TIME_FORMAT,
GST_TIME_ARGS (payload->ts));
demux->segment.start = payload->ts;
demux->segment.time = payload->ts;
} else {
GST_DEBUG_OBJECT (stream->pad, "Last queued payload has timestamp %"
GST_TIME_FORMAT " which is before our segment start %"
GST_TIME_FORMAT ", not pushing yet",
GST_TIME_ARGS (payload->ts),
GST_TIME_ARGS (demux->segment.start));
continue;
}
}
payload = NULL;
/* find first complete payload with timestamp */
for (j = 0;
j < stream->payloads->len && (payload == NULL
|| !GST_CLOCK_TIME_IS_VALID (payload->ts)); ++j) {
payload = &g_array_index (stream->payloads, AsfPayload, j);
}
/* Now see if there's a complete payload queued for this stream */
if (!gst_asf_payload_is_complete (payload))
continue;
}
/* ... and whether its timestamp is lower than the current best */
if (best_stream == NULL || best_payload->ts > payload->ts) {
best_stream = stream;
best_payload = payload;
}
}
}
return best_stream;
}
static GstFlowReturn
gst_asf_demux_push_complete_payloads (GstASFDemux * demux, gboolean force)
{
AsfStream *stream;
GstFlowReturn ret = GST_FLOW_OK;
if (G_UNLIKELY (!demux->activated_streams)) {
if (!gst_asf_demux_check_activate_streams (demux, force))
return GST_FLOW_OK;
/* streams are now activated */
}
while ((stream = gst_asf_demux_find_stream_with_complete_payload (demux))) {
AsfPayload *payload;
GstClockTime timestamp = GST_CLOCK_TIME_NONE;
GstClockTime duration = GST_CLOCK_TIME_NONE;
/* wait until we had a chance to "lock on" some payload's timestamp */
if (G_UNLIKELY (demux->need_newsegment
&& !GST_CLOCK_TIME_IS_VALID (demux->segment_ts)))
return GST_FLOW_OK;
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment) && stream->is_video
&& stream->payloads->len) {
payload = &g_array_index (stream->payloads, AsfPayload, stream->kf_pos);
} else {
payload = &g_array_index (stream->payloads, AsfPayload, 0);
}
/* do we need to send a newsegment event */
if ((G_UNLIKELY (demux->need_newsegment))) {
GstEvent *segment_event;
/* safe default if insufficient upstream info */
if (!GST_CLOCK_TIME_IS_VALID (demux->in_gap))
demux->in_gap = 0;
if (demux->segment.stop == GST_CLOCK_TIME_NONE &&
demux->segment.duration > 0) {
/* slight HACK; prevent clipping of last bit */
demux->segment.stop = demux->segment.duration + demux->in_gap;
}
/* FIXME : only if ACCURATE ! */
if (G_LIKELY (!demux->keyunit_sync && !demux->accurate
&& (GST_CLOCK_TIME_IS_VALID (payload->ts)))
&& !GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)) {
GST_DEBUG ("Adjusting newsegment start to %" GST_TIME_FORMAT,
GST_TIME_ARGS (payload->ts));
demux->segment.start = payload->ts;
demux->segment.time = payload->ts;
}
GST_DEBUG_OBJECT (demux, "sending new-segment event %" GST_SEGMENT_FORMAT,
&demux->segment);
/* note: we fix up all timestamps to start from 0, so this should be ok */
segment_event = gst_event_new_segment (&demux->segment);
if (demux->segment_seqnum)
gst_event_set_seqnum (segment_event, demux->segment_seqnum);
gst_asf_demux_send_event_unlocked (demux, segment_event);
/* now post any global tags we may have found */
if (demux->taglist == NULL) {
demux->taglist = gst_tag_list_new_empty ();
gst_tag_list_set_scope (demux->taglist, GST_TAG_SCOPE_GLOBAL);
}
gst_tag_list_add (demux->taglist, GST_TAG_MERGE_REPLACE,
GST_TAG_CONTAINER_FORMAT, "ASF", NULL);
GST_DEBUG_OBJECT (demux, "global tags: %" GST_PTR_FORMAT, demux->taglist);
gst_asf_demux_send_event_unlocked (demux,
gst_event_new_tag (demux->taglist));
demux->taglist = NULL;
demux->need_newsegment = FALSE;
demux->segment_seqnum = 0;
demux->segment_running = TRUE;
}
/* Do we have tags pending for this stream? */
if (G_UNLIKELY (stream->pending_tags)) {
GST_LOG_OBJECT (stream->pad, "%" GST_PTR_FORMAT, stream->pending_tags);
gst_pad_push_event (stream->pad,
gst_event_new_tag (stream->pending_tags));
stream->pending_tags = NULL;
}
/* We have the whole packet now so we should push the packet to
* the src pad now. First though we should check if we need to do
* descrambling */
if (G_UNLIKELY (stream->span > 1)) {
gst_asf_demux_descramble_buffer (demux, stream, &payload->buf);
}
payload->buf = gst_buffer_make_writable (payload->buf);
if (G_LIKELY (!payload->keyframe)) {
GST_BUFFER_FLAG_SET (payload->buf, GST_BUFFER_FLAG_DELTA_UNIT);
}
if (G_UNLIKELY (stream->discont)) {
GST_DEBUG_OBJECT (stream->pad, "marking DISCONT on stream");
GST_BUFFER_FLAG_SET (payload->buf, GST_BUFFER_FLAG_DISCONT);
stream->discont = FALSE;
}
if (G_UNLIKELY (stream->is_video && payload->par_x && payload->par_y &&
(payload->par_x != stream->par_x) &&
(payload->par_y != stream->par_y))) {
GST_DEBUG ("Updating PAR (%d/%d => %d/%d)",
stream->par_x, stream->par_y, payload->par_x, payload->par_y);
stream->par_x = payload->par_x;
stream->par_y = payload->par_y;
stream->caps = gst_caps_make_writable (stream->caps);
gst_caps_set_simple (stream->caps, "pixel-aspect-ratio",
GST_TYPE_FRACTION, stream->par_x, stream->par_y, NULL);
gst_pad_set_caps (stream->pad, stream->caps);
}
if (G_UNLIKELY (stream->interlaced != payload->interlaced)) {
GST_DEBUG ("Updating interlaced status (%d => %d)", stream->interlaced,
payload->interlaced);
stream->interlaced = payload->interlaced;
stream->caps = gst_caps_make_writable (stream->caps);
gst_caps_set_simple (stream->caps, "interlace-mode", G_TYPE_BOOLEAN,
(stream->interlaced ? "mixed" : "progressive"), NULL);
gst_pad_set_caps (stream->pad, stream->caps);
}
/* (sort of) interpolate timestamps using upstream "frame of reference",
* typically useful for live src, but might (unavoidably) mess with
* position reporting if a live src is playing not so live content
* (e.g. rtspsrc taking some time to fall back to tcp) */
timestamp = payload->ts;
if (GST_CLOCK_TIME_IS_VALID (timestamp)
&& !GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)) {
timestamp += demux->in_gap;
/* Check if we're after the segment already, if so no need to push
* anything here */
if (demux->segment.stop != -1 && timestamp > demux->segment.stop) {
GST_DEBUG_OBJECT (stream->pad,
"Payload after segment stop %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->segment.stop));
ret =
gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
GST_FLOW_EOS);
gst_buffer_unref (payload->buf);
payload->buf = NULL;
g_array_remove_index (stream->payloads, 0);
/* Break out as soon as we have an issue */
if (G_UNLIKELY (ret != GST_FLOW_OK))
break;
continue;
}
}
GST_BUFFER_PTS (payload->buf) = timestamp;
if (payload->duration == GST_CLOCK_TIME_NONE
&& stream->ext_props.avg_time_per_frame != 0) {
duration = stream->ext_props.avg_time_per_frame * 100;
} else {
duration = payload->duration;
}
GST_BUFFER_DURATION (payload->buf) = duration;
/* FIXME: we should really set durations on buffers if we can */
GST_LOG_OBJECT (stream->pad, "pushing buffer, %" GST_PTR_FORMAT,
payload->buf);
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment) && stream->is_video) {
if (stream->reverse_kf_ready == TRUE && stream->kf_pos == 0) {
GST_BUFFER_FLAG_SET (payload->buf, GST_BUFFER_FLAG_DISCONT);
}
} else if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)) {
GST_BUFFER_FLAG_SET (payload->buf, GST_BUFFER_FLAG_DISCONT);
}
if (stream->active) {
if (G_UNLIKELY (stream->first_buffer)) {
if (stream->streamheader != NULL) {
GST_DEBUG_OBJECT (stream->pad,
"Pushing streamheader before first buffer");
gst_pad_push (stream->pad, gst_buffer_ref (stream->streamheader));
}
stream->first_buffer = FALSE;
}
if (GST_CLOCK_TIME_IS_VALID (timestamp)
&& timestamp > demux->segment.position) {
demux->segment.position = timestamp;
if (GST_CLOCK_TIME_IS_VALID (duration))
demux->segment.position += timestamp;
}
ret = gst_pad_push (stream->pad, payload->buf);
ret =
gst_flow_combiner_update_pad_flow (demux->flowcombiner, stream->pad,
ret);
} else {
gst_buffer_unref (payload->buf);
ret = GST_FLOW_OK;
}
payload->buf = NULL;
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment) && stream->is_video
&& stream->reverse_kf_ready) {
g_array_remove_index (stream->payloads, stream->kf_pos);
stream->kf_pos--;
if (stream->reverse_kf_ready == TRUE && stream->kf_pos < 0) {
stream->kf_pos = 0;
stream->reverse_kf_ready = FALSE;
}
} else {
g_array_remove_index (stream->payloads, 0);
}
/* Break out as soon as we have an issue */
if (G_UNLIKELY (ret != GST_FLOW_OK))
break;
}
return ret;
}
static gboolean
gst_asf_demux_check_buffer_is_header (GstASFDemux * demux, GstBuffer * buf)
{
AsfObject obj;
GstMapInfo map;
gboolean valid;
g_assert (buf != NULL);
GST_LOG_OBJECT (demux, "Checking if buffer is a header");
gst_buffer_map (buf, &map, GST_MAP_READ);
/* we return false on buffer too small */
if (map.size < ASF_OBJECT_HEADER_SIZE) {
gst_buffer_unmap (buf, &map);
return FALSE;
}
/* check if it is a header */
valid =
asf_demux_peek_object (demux, map.data, ASF_OBJECT_HEADER_SIZE, &obj,
TRUE);
gst_buffer_unmap (buf, &map);
if (valid && obj.id == ASF_OBJ_HEADER) {
return TRUE;
}
return FALSE;
}
static gboolean
gst_asf_demux_check_chained_asf (GstASFDemux * demux)
{
guint64 off = demux->data_offset + (demux->packet * demux->packet_size);
GstFlowReturn ret = GST_FLOW_OK;
GstBuffer *buf = NULL;
gboolean header = FALSE;
/* TODO maybe we should skip index objects after the data and look
* further for a new header */
if (gst_asf_demux_pull_data (demux, off, ASF_OBJECT_HEADER_SIZE, &buf, &ret)) {
g_assert (buf != NULL);
/* check if it is a header */
if (gst_asf_demux_check_buffer_is_header (demux, buf)) {
GST_DEBUG_OBJECT (demux, "new base offset: %" G_GUINT64_FORMAT, off);
demux->base_offset = off;
header = TRUE;
}
gst_buffer_unref (buf);
}
return header;
}
static void
gst_asf_demux_loop (GstASFDemux * demux)
{
GstFlowReturn flow = GST_FLOW_OK;
GstBuffer *buf = NULL;
guint64 off;
if (G_UNLIKELY (demux->state == GST_ASF_DEMUX_STATE_HEADER)) {
if (!gst_asf_demux_pull_headers (demux, &flow)) {
goto pause;
}
flow = gst_asf_demux_pull_indices (demux);
if (flow != GST_FLOW_OK)
goto pause;
}
g_assert (demux->state == GST_ASF_DEMUX_STATE_DATA);
if (G_UNLIKELY (demux->num_packets != 0
&& demux->packet >= demux->num_packets))
goto eos;
GST_LOG_OBJECT (demux, "packet %u/%u", (guint) demux->packet + 1,
(guint) demux->num_packets);
off = demux->data_offset + (demux->packet * demux->packet_size);
if (G_UNLIKELY (!gst_asf_demux_pull_data (demux, off,
demux->packet_size * demux->speed_packets, &buf, &flow))) {
GST_DEBUG_OBJECT (demux, "got flow %s", gst_flow_get_name (flow));
if (flow == GST_FLOW_EOS) {
goto eos;
} else if (flow == GST_FLOW_FLUSHING) {
GST_DEBUG_OBJECT (demux, "Not fatal");
goto pause;
} else {
goto read_failed;
}
}
if (G_LIKELY (demux->speed_packets == 1)) {
GstAsfDemuxParsePacketError err;
err = gst_asf_demux_parse_packet (demux, buf);
if (G_UNLIKELY (err != GST_ASF_DEMUX_PARSE_PACKET_ERROR_NONE)) {
/* when we don't know when the data object ends, we should check
* for a chained asf */
if (demux->num_packets == 0) {
if (gst_asf_demux_check_buffer_is_header (demux, buf)) {
GST_INFO_OBJECT (demux, "Chained asf found");
demux->base_offset = off;
gst_asf_demux_reset (demux, TRUE);
gst_buffer_unref (buf);
return;
}
}
/* FIXME: We should tally up fatal errors and error out only
* after a few broken packets in a row? */
GST_INFO_OBJECT (demux, "Ignoring recoverable parse error");
gst_buffer_unref (buf);
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)
&& !demux->seek_to_cur_pos) {
--demux->packet;
if (demux->packet < 0) {
goto eos;
}
} else {
++demux->packet;
}
return;
}
flow = gst_asf_demux_push_complete_payloads (demux, FALSE);
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)
&& !demux->seek_to_cur_pos) {
--demux->packet;
if (demux->packet < 0) {
goto eos;
}
} else {
++demux->packet;
}
} else {
guint n;
for (n = 0; n < demux->speed_packets; n++) {
GstBuffer *sub;
GstAsfDemuxParsePacketError err;
sub =
gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL,
n * demux->packet_size, demux->packet_size);
err = gst_asf_demux_parse_packet (demux, sub);
if (G_UNLIKELY (err != GST_ASF_DEMUX_PARSE_PACKET_ERROR_NONE)) {
/* when we don't know when the data object ends, we should check
* for a chained asf */
if (demux->num_packets == 0) {
if (gst_asf_demux_check_buffer_is_header (demux, sub)) {
GST_INFO_OBJECT (demux, "Chained asf found");
demux->base_offset = off + n * demux->packet_size;
gst_asf_demux_reset (demux, TRUE);
gst_buffer_unref (sub);
gst_buffer_unref (buf);
return;
}
}
/* FIXME: We should tally up fatal errors and error out only
* after a few broken packets in a row? */
GST_INFO_OBJECT (demux, "Ignoring recoverable parse error");
flow = GST_FLOW_OK;
}
gst_buffer_unref (sub);
if (err == GST_ASF_DEMUX_PARSE_PACKET_ERROR_NONE)
flow = gst_asf_demux_push_complete_payloads (demux, FALSE);
++demux->packet;
}
/* reset speed pull */
demux->speed_packets = 1;
}
gst_buffer_unref (buf);
if (G_UNLIKELY ((demux->num_packets > 0
&& demux->packet >= demux->num_packets)
|| flow == GST_FLOW_EOS)) {
GST_LOG_OBJECT (demux, "reached EOS");
goto eos;
}
if (G_UNLIKELY (flow != GST_FLOW_OK)) {
GST_DEBUG_OBJECT (demux, "pushing complete payloads failed");
goto pause;
}
/* check if we're at the end of the configured segment */
/* FIXME: check if segment end reached etc. */
return;
eos:
{
/* if we haven't activated our streams yet, this might be because we have
* less data queued than required for preroll; force stream activation and
* send any pending payloads before sending EOS */
if (!demux->activated_streams)
flow = gst_asf_demux_push_complete_payloads (demux, TRUE);
/* we want to push an eos or post a segment-done in any case */
if (demux->segment.flags & GST_SEEK_FLAG_SEGMENT) {
gint64 stop;
/* for segment playback we need to post when (in stream time)
* we stopped, this is either stop (when set) or the duration. */
if ((stop = demux->segment.stop) == -1)
stop = demux->segment.duration;
GST_INFO_OBJECT (demux, "Posting segment-done, at end of segment");
gst_element_post_message (GST_ELEMENT_CAST (demux),
gst_message_new_segment_done (GST_OBJECT (demux), GST_FORMAT_TIME,
stop));
gst_asf_demux_send_event_unlocked (demux,
gst_event_new_segment_done (GST_FORMAT_TIME, stop));
} else if (flow != GST_FLOW_EOS) {
/* check if we have a chained asf, in case, we don't eos yet */
if (gst_asf_demux_check_chained_asf (demux)) {
GST_INFO_OBJECT (demux, "Chained ASF starting");
gst_asf_demux_reset (demux, TRUE);
return;
}
}
if (!(demux->segment.flags & GST_SEEK_FLAG_SEGMENT)) {
if (demux->activated_streams) {
/* normal playback, send EOS to all linked pads */
GST_INFO_OBJECT (demux, "Sending EOS, at end of stream");
gst_asf_demux_send_event_unlocked (demux, gst_event_new_eos ());
} else {
GST_WARNING_OBJECT (demux, "EOS without exposed streams");
flow = GST_FLOW_EOS;
}
}
/* ... and fall through to pause */
}
pause:
{
GST_DEBUG_OBJECT (demux, "pausing task, flow return: %s",
gst_flow_get_name (flow));
demux->segment_running = FALSE;
gst_pad_pause_task (demux->sinkpad);
/* For the error cases */
if (flow == GST_FLOW_EOS && !demux->activated_streams) {
GST_ELEMENT_ERROR (demux, STREAM, WRONG_TYPE, (NULL),
("This doesn't seem to be an ASF file"));
} else if (flow < GST_FLOW_EOS || flow == GST_FLOW_NOT_LINKED) {
/* Post an error. Hopefully something else already has, but if not... */
GST_ELEMENT_FLOW_ERROR (demux, flow);
gst_asf_demux_send_event_unlocked (demux, gst_event_new_eos ());
}
return;
}
/* ERRORS */
read_failed:
{
GST_DEBUG_OBJECT (demux, "Read failed, doh");
flow = GST_FLOW_EOS;
goto pause;
}
#if 0
/* See FIXMEs above */
parse_error:
{
gst_buffer_unref (buf);
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("Error parsing ASF packet %u", (guint) demux->packet));
gst_asf_demux_send_event_unlocked (demux, gst_event_new_eos ());
flow = GST_FLOW_ERROR;
goto pause;
}
#endif
}
#define GST_ASF_DEMUX_CHECK_HEADER_YES 0
#define GST_ASF_DEMUX_CHECK_HEADER_NO 1
#define GST_ASF_DEMUX_CHECK_HEADER_NEED_DATA 2
static gint
gst_asf_demux_check_header (GstASFDemux * demux)
{
AsfObject obj;
guint8 *cdata = (guint8 *) gst_adapter_map (demux->adapter,
ASF_OBJECT_HEADER_SIZE);
if (cdata == NULL) /* need more data */
return GST_ASF_DEMUX_CHECK_HEADER_NEED_DATA;
if (asf_demux_peek_object (demux, cdata, ASF_OBJECT_HEADER_SIZE, &obj, FALSE
&& obj.id == ASF_OBJ_HEADER))
return GST_ASF_DEMUX_CHECK_HEADER_YES;
return GST_ASF_DEMUX_CHECK_HEADER_NO;
}
static GstFlowReturn
gst_asf_demux_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
{
GstFlowReturn ret = GST_FLOW_OK;
GstASFDemux *demux;
demux = GST_ASF_DEMUX (parent);
GST_LOG_OBJECT (demux,
"buffer: size=%" G_GSIZE_FORMAT ", offset=%" G_GINT64_FORMAT ", time=%"
GST_TIME_FORMAT, gst_buffer_get_size (buf), GST_BUFFER_OFFSET (buf),
GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
if (G_UNLIKELY (GST_BUFFER_IS_DISCONT (buf))) {
GST_DEBUG_OBJECT (demux, "received DISCONT");
gst_asf_demux_mark_discont (demux);
}
if (G_UNLIKELY ((!GST_CLOCK_TIME_IS_VALID (demux->in_gap) &&
GST_BUFFER_TIMESTAMP_IS_VALID (buf)))) {
demux->in_gap = GST_BUFFER_TIMESTAMP (buf) - demux->in_segment.start;
GST_DEBUG_OBJECT (demux, "upstream segment start %" GST_TIME_FORMAT
", interpolation gap: %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->in_segment.start), GST_TIME_ARGS (demux->in_gap));
}
gst_adapter_push (demux->adapter, buf);
switch (demux->state) {
case GST_ASF_DEMUX_STATE_INDEX:{
gint result = gst_asf_demux_check_header (demux);
if (result == GST_ASF_DEMUX_CHECK_HEADER_NEED_DATA) /* need more data */
break;
if (result == GST_ASF_DEMUX_CHECK_HEADER_NO) {
/* we don't care about this, probably an index */
/* TODO maybe would be smarter to skip all the indices
* until we got a new header or EOS to decide */
GST_LOG_OBJECT (demux, "Received index object, its EOS");
goto eos;
} else {
GST_INFO_OBJECT (demux, "Chained asf starting");
/* cleanup and get ready for a chained asf */
gst_asf_demux_reset (demux, TRUE);
/* fall through */
}
}
case GST_ASF_DEMUX_STATE_HEADER:{
ret = gst_asf_demux_chain_headers (demux);
if (demux->state != GST_ASF_DEMUX_STATE_DATA)
break;
/* otherwise fall through */
}
case GST_ASF_DEMUX_STATE_DATA:
{
guint64 data_size;
data_size = demux->packet_size;
while (gst_adapter_available (demux->adapter) >= data_size) {
GstBuffer *buf;
GstAsfDemuxParsePacketError err;
/* we don't know the length of the stream
* check for a chained asf everytime */
if (demux->num_packets == 0) {
gint result = gst_asf_demux_check_header (demux);
if (result == GST_ASF_DEMUX_CHECK_HEADER_YES) {
GST_INFO_OBJECT (demux, "Chained asf starting");
/* cleanup and get ready for a chained asf */
gst_asf_demux_reset (demux, TRUE);
break;
}
} else if (G_UNLIKELY (demux->num_packets != 0 && demux->packet >= 0
&& demux->packet >= demux->num_packets)) {
/* do not overshoot data section when streaming */
break;
}
buf = gst_adapter_take_buffer (demux->adapter, data_size);
/* FIXME: We should tally up fatal errors and error out only
* after a few broken packets in a row? */
err = gst_asf_demux_parse_packet (demux, buf);
gst_buffer_unref (buf);
if (G_LIKELY (err == GST_ASF_DEMUX_PARSE_PACKET_ERROR_NONE))
ret = gst_asf_demux_push_complete_payloads (demux, FALSE);
else
GST_WARNING_OBJECT (demux, "Parse error");
if (demux->packet >= 0)
++demux->packet;
}
if (G_UNLIKELY (demux->num_packets != 0 && demux->packet >= 0
&& demux->packet >= demux->num_packets)) {
demux->state = GST_ASF_DEMUX_STATE_INDEX;
}
break;
}
default:
g_assert_not_reached ();
}
done:
if (ret != GST_FLOW_OK)
GST_DEBUG_OBJECT (demux, "flow: %s", gst_flow_get_name (ret));
return ret;
eos:
{
GST_DEBUG_OBJECT (demux, "Handled last packet, setting EOS");
ret = GST_FLOW_EOS;
goto done;
}
}
static inline gboolean
gst_asf_demux_skip_bytes (guint num_bytes, guint8 ** p_data, guint64 * p_size)
{
if (*p_size < num_bytes)
return FALSE;
*p_data += num_bytes;
*p_size -= num_bytes;
return TRUE;
}
static inline guint8
gst_asf_demux_get_uint8 (guint8 ** p_data, guint64 * p_size)
{
guint8 ret;
g_assert (*p_size >= 1);
ret = GST_READ_UINT8 (*p_data);
*p_data += sizeof (guint8);
*p_size -= sizeof (guint8);
return ret;
}
static inline guint16
gst_asf_demux_get_uint16 (guint8 ** p_data, guint64 * p_size)
{
guint16 ret;
g_assert (*p_size >= 2);
ret = GST_READ_UINT16_LE (*p_data);
*p_data += sizeof (guint16);
*p_size -= sizeof (guint16);
return ret;
}
static inline guint32
gst_asf_demux_get_uint32 (guint8 ** p_data, guint64 * p_size)
{
guint32 ret;
g_assert (*p_size >= 4);
ret = GST_READ_UINT32_LE (*p_data);
*p_data += sizeof (guint32);
*p_size -= sizeof (guint32);
return ret;
}
static inline guint64
gst_asf_demux_get_uint64 (guint8 ** p_data, guint64 * p_size)
{
guint64 ret;
g_assert (*p_size >= 8);
ret = GST_READ_UINT64_LE (*p_data);
*p_data += sizeof (guint64);
*p_size -= sizeof (guint64);
return ret;
}
static gboolean
gst_asf_demux_get_buffer (GstBuffer ** p_buf, guint num_bytes_to_read,
guint8 ** p_data, guint64 * p_size)
{
*p_buf = NULL;
if (*p_size < num_bytes_to_read)
return FALSE;
*p_buf = gst_buffer_new_and_alloc (num_bytes_to_read);
gst_buffer_fill (*p_buf, 0, *p_data, num_bytes_to_read);
*p_data += num_bytes_to_read;
*p_size -= num_bytes_to_read;
return TRUE;
}
static gboolean
gst_asf_demux_get_bytes (guint8 ** p_buf, guint num_bytes_to_read,
guint8 ** p_data, guint64 * p_size)
{
*p_buf = NULL;
if (*p_size < num_bytes_to_read)
return FALSE;
*p_buf = g_memdup (*p_data, num_bytes_to_read);
*p_data += num_bytes_to_read;
*p_size -= num_bytes_to_read;
return TRUE;
}
static gboolean
gst_asf_demux_get_string (gchar ** p_str, guint16 * p_strlen,
guint8 ** p_data, guint64 * p_size)
{
guint16 s_length;
guint8 *s;
*p_str = NULL;
if (*p_size < 2)
return FALSE;
s_length = gst_asf_demux_get_uint16 (p_data, p_size);
if (p_strlen)
*p_strlen = s_length;
if (s_length == 0) {
GST_WARNING ("zero-length string");
*p_str = g_strdup ("");
return TRUE;
}
if (!gst_asf_demux_get_bytes (&s, s_length, p_data, p_size))
return FALSE;
g_assert (s != NULL);
/* just because They don't exist doesn't
* mean They are not out to get you ... */
if (s[s_length - 1] != '\0') {
s = g_realloc (s, s_length + 1);
s[s_length] = '\0';
}
*p_str = (gchar *) s;
return TRUE;
}
static void
gst_asf_demux_get_guid (ASFGuid * guid, guint8 ** p_data, guint64 * p_size)
{
g_assert (*p_size >= 4 * sizeof (guint32));
guid->v1 = gst_asf_demux_get_uint32 (p_data, p_size);
guid->v2 = gst_asf_demux_get_uint32 (p_data, p_size);
guid->v3 = gst_asf_demux_get_uint32 (p_data, p_size);
guid->v4 = gst_asf_demux_get_uint32 (p_data, p_size);
}
static gboolean
gst_asf_demux_get_stream_audio (asf_stream_audio * audio, guint8 ** p_data,
guint64 * p_size)
{
if (*p_size < (2 + 2 + 4 + 4 + 2 + 2 + 2))
return FALSE;
/* WAVEFORMATEX Structure */
audio->codec_tag = gst_asf_demux_get_uint16 (p_data, p_size);
audio->channels = gst_asf_demux_get_uint16 (p_data, p_size);
audio->sample_rate = gst_asf_demux_get_uint32 (p_data, p_size);
audio->byte_rate = gst_asf_demux_get_uint32 (p_data, p_size);
audio->block_align = gst_asf_demux_get_uint16 (p_data, p_size);
audio->word_size = gst_asf_demux_get_uint16 (p_data, p_size);
/* Codec specific data size */
audio->size = gst_asf_demux_get_uint16 (p_data, p_size);
if (audio->size > *p_size) {
GST_WARNING ("Corrupted audio codec_data (should be at least %u bytes, is %"
G_GUINT64_FORMAT " long)", audio->size, *p_size);
return FALSE;
}
return TRUE;
}
static gboolean
gst_asf_demux_get_stream_video (asf_stream_video * video, guint8 ** p_data,
guint64 * p_size)
{
if (*p_size < (4 + 4 + 1 + 2))
return FALSE;
video->width = gst_asf_demux_get_uint32 (p_data, p_size);
video->height = gst_asf_demux_get_uint32 (p_data, p_size);
video->unknown = gst_asf_demux_get_uint8 (p_data, p_size);
video->size = gst_asf_demux_get_uint16 (p_data, p_size);
return TRUE;
}
static gboolean
gst_asf_demux_get_stream_video_format (asf_stream_video_format * fmt,
guint8 ** p_data, guint64 * p_size)
{
if (*p_size < (4 + 4 + 4 + 2 + 2 + 4 + 4 + 4 + 4 + 4 + 4))
return FALSE;
fmt->size = gst_asf_demux_get_uint32 (p_data, p_size);
/* Sanity checks */
if (fmt->size < 40) {
GST_WARNING ("Corrupted asf_stream_video_format (size < 40)");
return FALSE;
}
if ((guint64) fmt->size - 4 > *p_size) {
GST_WARNING ("Corrupted asf_stream_video_format (codec_data is too small)");
return FALSE;
}
fmt->width = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->height = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->planes = gst_asf_demux_get_uint16 (p_data, p_size);
fmt->depth = gst_asf_demux_get_uint16 (p_data, p_size);
fmt->tag = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->image_size = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->xpels_meter = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->ypels_meter = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->num_colors = gst_asf_demux_get_uint32 (p_data, p_size);
fmt->imp_colors = gst_asf_demux_get_uint32 (p_data, p_size);
return TRUE;
}
AsfStream *
gst_asf_demux_get_stream (GstASFDemux * demux, guint16 id)
{
guint i;
for (i = 0; i < demux->num_streams; i++) {
if (demux->stream[i].id == id)
return &demux->stream[i];
}
if (gst_asf_demux_is_unknown_stream (demux, id))
GST_WARNING ("Segment found for undefined stream: (%d)", id);
return NULL;
}
static AsfStream *
gst_asf_demux_setup_pad (GstASFDemux * demux, GstPad * src_pad,
GstCaps * caps, guint16 id, gboolean is_video, GstBuffer * streamheader,
GstTagList * tags)
{
AsfStream *stream;
gst_pad_use_fixed_caps (src_pad);
gst_pad_set_caps (src_pad, caps);
gst_pad_set_event_function (src_pad,
GST_DEBUG_FUNCPTR (gst_asf_demux_handle_src_event));
gst_pad_set_query_function (src_pad,
GST_DEBUG_FUNCPTR (gst_asf_demux_handle_src_query));
stream = &demux->stream[demux->num_streams];
stream->caps = caps;
stream->pad = src_pad;
stream->id = id;
stream->fps_known = !is_video; /* bit hacky for audio */
stream->is_video = is_video;
stream->pending_tags = tags;
stream->discont = TRUE;
stream->first_buffer = TRUE;
stream->streamheader = streamheader;
if (stream->streamheader) {
stream->streamheader = gst_buffer_make_writable (streamheader);
GST_BUFFER_FLAG_SET (stream->streamheader, GST_BUFFER_FLAG_HEADER);
}
if (is_video) {
GstStructure *st;
gint par_x, par_y;
st = gst_caps_get_structure (caps, 0);
if (gst_structure_get_fraction (st, "pixel-aspect-ratio", &par_x, &par_y) &&
par_x > 0 && par_y > 0) {
GST_DEBUG ("PAR %d/%d", par_x, par_y);
stream->par_x = par_x;
stream->par_y = par_y;
}
}
stream->payloads = g_array_new (FALSE, FALSE, sizeof (AsfPayload));
/* TODO: create this array during reverse play? */
stream->payloads_rev = g_array_new (FALSE, FALSE, sizeof (AsfPayload));
GST_INFO ("Created pad %s for stream %u with caps %" GST_PTR_FORMAT,
GST_PAD_NAME (src_pad), demux->num_streams, caps);
++demux->num_streams;
stream->active = FALSE;
return stream;
}
static void
gst_asf_demux_add_stream_headers_to_caps (GstASFDemux * demux,
GstBuffer * buffer, GstStructure * structure)
{
GValue arr_val = G_VALUE_INIT;
GValue buf_val = G_VALUE_INIT;
g_value_init (&arr_val, GST_TYPE_ARRAY);
g_value_init (&buf_val, GST_TYPE_BUFFER);
gst_value_set_buffer (&buf_val, buffer);
gst_value_array_append_and_take_value (&arr_val, &buf_val);
gst_structure_take_value (structure, "streamheader", &arr_val);
}
static AsfStream *
gst_asf_demux_add_audio_stream (GstASFDemux * demux,
asf_stream_audio * audio, guint16 id, guint8 ** p_data, guint64 * p_size)
{
GstTagList *tags = NULL;
GstBuffer *extradata = NULL;
GstPad *src_pad;
GstCaps *caps;
guint16 size_left = 0;
gchar *codec_name = NULL;
gchar *name = NULL;
size_left = audio->size;
/* Create the audio pad */
name = g_strdup_printf ("audio_%u", demux->num_audio_streams);
src_pad = gst_pad_new_from_static_template (&audio_src_template, name);
g_free (name);
/* Swallow up any left over data and set up the
* standard properties from the header info */
if (size_left) {
GST_INFO_OBJECT (demux, "Audio header contains %d bytes of "
"codec specific data", size_left);
g_assert (size_left <= *p_size);
gst_asf_demux_get_buffer (&extradata, size_left, p_data, p_size);
}
/* asf_stream_audio is the same as gst_riff_strf_auds, but with an
* additional two bytes indicating extradata. */
/* FIXME: Handle the channel reorder map here */
caps = gst_riff_create_audio_caps (audio->codec_tag, NULL,
(gst_riff_strf_auds *) audio, extradata, NULL, &codec_name, NULL);
if (caps == NULL) {
caps = gst_caps_new_simple ("audio/x-asf-unknown", "codec_id",
G_TYPE_INT, (gint) audio->codec_tag, NULL);
}
/* Informing about that audio format we just added */
if (codec_name) {
tags = gst_tag_list_new (GST_TAG_AUDIO_CODEC, codec_name, NULL);
g_free (codec_name);
}
if (audio->byte_rate > 0) {
/* Some ASF files have no bitrate props object (often seen with
* ASF files that contain raw audio data). Example files can
* be generated with FFmpeg (tested with v2.8.6), like this:
*
* ffmpeg -i sine-wave.wav -c:a pcm_alaw file.asf
*
* In this case, if audio->byte_rate is nonzero, use that as
* the bitrate. */
guint bitrate = audio->byte_rate * 8;
if (tags == NULL)
tags = gst_tag_list_new_empty ();
/* Add bitrate, but only if there is none set already, since
* this is just a fallback in case there is no bitrate tag
* already present */
gst_tag_list_add (tags, GST_TAG_MERGE_KEEP, GST_TAG_BITRATE, bitrate, NULL);
}
if (extradata)
gst_buffer_unref (extradata);
GST_INFO ("Adding audio stream #%u, id %u codec %u (0x%04x), tags=%"
GST_PTR_FORMAT, demux->num_audio_streams, id, audio->codec_tag,
audio->codec_tag, tags);
++demux->num_audio_streams;
return gst_asf_demux_setup_pad (demux, src_pad, caps, id, FALSE, NULL, tags);
}
static AsfStream *
gst_asf_demux_add_video_stream (GstASFDemux * demux,
asf_stream_video_format * video, guint16 id,
guint8 ** p_data, guint64 * p_size)
{
GstTagList *tags = NULL;
GstStructure *caps_s;
GstBuffer *extradata = NULL;
GstPad *src_pad;
GstCaps *caps;
gchar *str;
gchar *name = NULL;
gchar *codec_name = NULL;
guint64 size_left = video->size - 40;
GstBuffer *streamheader = NULL;
guint par_w = 1, par_h = 1;
/* Create the video pad */
name = g_strdup_printf ("video_%u", demux->num_video_streams);
src_pad = gst_pad_new_from_static_template (&video_src_template, name);
g_free (name);
/* Now try some gstreamer formatted MIME types (from gst_avi_demux_strf_vids) */
if (size_left) {
GST_LOG ("Video header has %" G_GUINT64_FORMAT
" bytes of codec specific data (vs %" G_GUINT64_FORMAT ")", size_left,
*p_size);
g_assert (size_left <= *p_size);
gst_asf_demux_get_buffer (&extradata, size_left, p_data, p_size);
}
GST_DEBUG ("video codec %" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (video->tag));
/* yes, asf_stream_video_format and gst_riff_strf_vids are the same */
caps = gst_riff_create_video_caps (video->tag, NULL,
(gst_riff_strf_vids *) video, extradata, NULL, &codec_name);
if (caps == NULL) {
caps = gst_caps_new_simple ("video/x-asf-unknown", "fourcc",
G_TYPE_UINT, video->tag, NULL);
} else {
GstStructure *s;
gint ax, ay;
s = gst_asf_demux_get_metadata_for_stream (demux, id);
if (gst_structure_get_int (s, "AspectRatioX", &ax) &&
gst_structure_get_int (s, "AspectRatioY", &ay) && (ax > 0 && ay > 0)) {
par_w = ax;
par_h = ay;
gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
ax, ay, NULL);
} else {
guint ax, ay;
/* retry with the global metadata */
GST_DEBUG ("Retrying with global metadata %" GST_PTR_FORMAT,
demux->global_metadata);
s = demux->global_metadata;
if (gst_structure_get_uint (s, "AspectRatioX", &ax) &&
gst_structure_get_uint (s, "AspectRatioY", &ay)) {
GST_DEBUG ("ax:%d, ay:%d", ax, ay);
if (ax > 0 && ay > 0) {
par_w = ax;
par_h = ay;
gst_caps_set_simple (caps, "pixel-aspect-ratio", GST_TYPE_FRACTION,
ax, ay, NULL);
}
}
}
s = gst_caps_get_structure (caps, 0);
gst_structure_remove_field (s, "framerate");
}
caps_s = gst_caps_get_structure (caps, 0);
/* add format field with fourcc to WMV/VC1 caps to differentiate variants */
if (gst_structure_has_name (caps_s, "video/x-wmv")) {
str = g_strdup_printf ("%" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (video->tag));
gst_caps_set_simple (caps, "format", G_TYPE_STRING, str, NULL);
g_free (str);
/* check if h264 has codec_data (avc) or streamheaders (bytestream) */
} else if (gst_structure_has_name (caps_s, "video/x-h264")) {
const GValue *value = gst_structure_get_value (caps_s, "codec_data");
if (value) {
GstBuffer *buf = gst_value_get_buffer (value);
GstMapInfo mapinfo;
if (gst_buffer_map (buf, &mapinfo, GST_MAP_READ)) {
if (mapinfo.size >= 4 && GST_READ_UINT32_BE (mapinfo.data) == 1) {
/* this looks like a bytestream start */
streamheader = gst_buffer_ref (buf);
gst_asf_demux_add_stream_headers_to_caps (demux, buf, caps_s);
gst_structure_remove_field (caps_s, "codec_data");
}
gst_buffer_unmap (buf, &mapinfo);
}
}
}
/* For a 3D video, set multiview information into the caps based on
* what was detected during object parsing */
if (demux->asf_3D_mode != GST_ASF_3D_NONE) {
GstVideoMultiviewMode mv_mode = GST_VIDEO_MULTIVIEW_MODE_NONE;
GstVideoMultiviewFlags mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_NONE;
const gchar *mview_mode_str;
switch (demux->asf_3D_mode) {
case GST_ASF_3D_SIDE_BY_SIDE_HALF_LR:
mv_mode = GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
break;
case GST_ASF_3D_SIDE_BY_SIDE_HALF_RL:
mv_mode = GST_VIDEO_MULTIVIEW_MODE_SIDE_BY_SIDE;
mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
break;
case GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR:
mv_mode = GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM;
break;
case GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL:
mv_mode = GST_VIDEO_MULTIVIEW_MODE_TOP_BOTTOM;
mv_flags = GST_VIDEO_MULTIVIEW_FLAGS_RIGHT_VIEW_FIRST;
break;
case GST_ASF_3D_DUAL_STREAM:{
gboolean is_right_view = FALSE;
/* if Advanced_Mutual_Exclusion object exists, use it
* to figure out which is the left view (lower ID) */
if (demux->mut_ex_streams != NULL) {
guint length;
gint i;
length = g_slist_length (demux->mut_ex_streams);
for (i = 0; i < length; i++) {
gpointer v_s_id;
v_s_id = g_slist_nth_data (demux->mut_ex_streams, i);
GST_DEBUG_OBJECT (demux,
"has Mutual_Exclusion object. stream id in object is %d",
GPOINTER_TO_INT (v_s_id));
if (id > GPOINTER_TO_INT (v_s_id))
is_right_view = TRUE;
}
} else {
/* if the Advaced_Mutual_Exclusion object doesn't exist, assume the
* first video stream encountered has the lower ID */
if (demux->num_video_streams > 0) {
/* This is not the first video stream, assuming right eye view */
is_right_view = TRUE;
}
}
if (is_right_view)
mv_mode = GST_VIDEO_MULTIVIEW_MODE_RIGHT;
else
mv_mode = GST_VIDEO_MULTIVIEW_MODE_LEFT;
break;
}
default:
break;
}
GST_INFO_OBJECT (demux,
"stream_id %d, has multiview-mode %d flags 0x%x", id, mv_mode,
(guint) mv_flags);
mview_mode_str = gst_video_multiview_mode_to_caps_string (mv_mode);
if (mview_mode_str != NULL) {
if (gst_video_multiview_guess_half_aspect (mv_mode, video->width,
video->height, par_w, par_h))
mv_flags |= GST_VIDEO_MULTIVIEW_FLAGS_HALF_ASPECT;
gst_caps_set_simple (caps,
"multiview-mode", G_TYPE_STRING, mview_mode_str,
"multiview-flags", GST_TYPE_VIDEO_MULTIVIEW_FLAGSET, mv_flags,
GST_FLAG_SET_MASK_EXACT, NULL);
}
}
if (codec_name) {
tags = gst_tag_list_new (GST_TAG_VIDEO_CODEC, codec_name, NULL);
g_free (codec_name);
}
if (extradata)
gst_buffer_unref (extradata);
GST_INFO ("Adding video stream #%u, id %u, codec %"
GST_FOURCC_FORMAT " (0x%08x)", demux->num_video_streams, id,
GST_FOURCC_ARGS (video->tag), video->tag);
++demux->num_video_streams;
return gst_asf_demux_setup_pad (demux, src_pad, caps, id, TRUE,
streamheader, tags);
}
static void
gst_asf_demux_activate_stream (GstASFDemux * demux, AsfStream * stream)
{
if (!stream->active) {
GstEvent *event;
gchar *stream_id;
GST_INFO_OBJECT (demux, "Activating stream %2u, pad %s, caps %"
GST_PTR_FORMAT, stream->id, GST_PAD_NAME (stream->pad), stream->caps);
gst_pad_set_active (stream->pad, TRUE);
stream_id =
gst_pad_create_stream_id_printf (stream->pad, GST_ELEMENT_CAST (demux),
"%03u", stream->id);
event =
gst_pad_get_sticky_event (demux->sinkpad, GST_EVENT_STREAM_START, 0);
if (event) {
if (gst_event_parse_group_id (event, &demux->group_id))
demux->have_group_id = TRUE;
else
demux->have_group_id = FALSE;
gst_event_unref (event);
} else if (!demux->have_group_id) {
demux->have_group_id = TRUE;
demux->group_id = gst_util_group_id_next ();
}
event = gst_event_new_stream_start (stream_id);
if (demux->have_group_id)
gst_event_set_group_id (event, demux->group_id);
gst_pad_push_event (stream->pad, event);
g_free (stream_id);
gst_pad_set_caps (stream->pad, stream->caps);
gst_element_add_pad (GST_ELEMENT_CAST (demux), stream->pad);
gst_flow_combiner_add_pad (demux->flowcombiner, stream->pad);
stream->active = TRUE;
}
}
static AsfStream *
gst_asf_demux_parse_stream_object (GstASFDemux * demux, guint8 * data,
guint64 size)
{
AsfCorrectionType correction_type;
AsfStreamType stream_type;
GstClockTime time_offset;
gboolean is_encrypted G_GNUC_UNUSED;
guint16 stream_id;
guint16 flags;
ASFGuid guid;
guint stream_specific_size;
guint type_specific_size G_GNUC_UNUSED;
guint unknown G_GNUC_UNUSED;
gboolean inspect_payload = FALSE;
AsfStream *stream = NULL;
/* Get the rest of the header's header */
if (size < (16 + 16 + 8 + 4 + 4 + 2 + 4))
goto not_enough_data;
gst_asf_demux_get_guid (&guid, &data, &size);
stream_type = gst_asf_demux_identify_guid (asf_stream_guids, &guid);
gst_asf_demux_get_guid (&guid, &data, &size);
correction_type = gst_asf_demux_identify_guid (asf_correction_guids, &guid);
time_offset = gst_asf_demux_get_uint64 (&data, &size) * 100;
type_specific_size = gst_asf_demux_get_uint32 (&data, &size);
stream_specific_size = gst_asf_demux_get_uint32 (&data, &size);
flags = gst_asf_demux_get_uint16 (&data, &size);
stream_id = flags & 0x7f;
is_encrypted = ! !((flags & 0x8000) << 15);
unknown = gst_asf_demux_get_uint32 (&data, &size);
GST_DEBUG_OBJECT (demux, "Found stream %u, time_offset=%" GST_TIME_FORMAT,
stream_id, GST_TIME_ARGS (time_offset));
/* dvr-ms has audio stream declared in stream specific data */
if (stream_type == ASF_STREAM_EXT_EMBED_HEADER) {
AsfExtStreamType ext_stream_type;
gst_asf_demux_get_guid (&guid, &data, &size);
ext_stream_type = gst_asf_demux_identify_guid (asf_ext_stream_guids, &guid);
if (ext_stream_type == ASF_EXT_STREAM_AUDIO) {
inspect_payload = TRUE;
gst_asf_demux_get_guid (&guid, &data, &size);
gst_asf_demux_get_uint32 (&data, &size);
gst_asf_demux_get_uint32 (&data, &size);
gst_asf_demux_get_uint32 (&data, &size);
gst_asf_demux_get_guid (&guid, &data, &size);
gst_asf_demux_get_uint32 (&data, &size);
stream_type = ASF_STREAM_AUDIO;
}
}
switch (stream_type) {
case ASF_STREAM_AUDIO:{
asf_stream_audio audio_object;
if (!gst_asf_demux_get_stream_audio (&audio_object, &data, &size))
goto not_enough_data;
GST_INFO ("Object is an audio stream with %u bytes of additional data",
audio_object.size);
stream = gst_asf_demux_add_audio_stream (demux, &audio_object, stream_id,
&data, &size);
switch (correction_type) {
case ASF_CORRECTION_ON:{
guint span, packet_size, chunk_size, data_size, silence_data;
GST_INFO ("Using error correction");
if (size < (1 + 2 + 2 + 2 + 1))
goto not_enough_data;
span = gst_asf_demux_get_uint8 (&data, &size);
packet_size = gst_asf_demux_get_uint16 (&data, &size);
chunk_size = gst_asf_demux_get_uint16 (&data, &size);
data_size = gst_asf_demux_get_uint16 (&data, &size);
silence_data = gst_asf_demux_get_uint8 (&data, &size);
stream->span = span;
GST_DEBUG_OBJECT (demux, "Descrambling ps:%u cs:%u ds:%u s:%u sd:%u",
packet_size, chunk_size, data_size, span, silence_data);
if (stream->span > 1) {
if (chunk_size == 0 || ((packet_size / chunk_size) <= 1)) {
/* Disable descrambling */
stream->span = 0;
} else {
/* FIXME: this else branch was added for
* weird_al_yankovic - the saga begins.asf */
stream->ds_packet_size = packet_size;
stream->ds_chunk_size = chunk_size;
}
} else {
/* Descambling is enabled */
stream->ds_packet_size = packet_size;
stream->ds_chunk_size = chunk_size;
}
#if 0
/* Now skip the rest of the silence data */
if (data_size > 1)
gst_bytestream_flush (demux->bs, data_size - 1);
#else
/* FIXME: CHECKME. And why -1? */
if (data_size > 1) {
if (!gst_asf_demux_skip_bytes (data_size - 1, &data, &size)) {
goto not_enough_data;
}
}
#endif
break;
}
case ASF_CORRECTION_OFF:{
GST_INFO ("Error correction off");
if (!gst_asf_demux_skip_bytes (stream_specific_size, &data, &size))
goto not_enough_data;
break;
}
default:
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("Audio stream using unknown error correction"));
return NULL;
}
break;
}
case ASF_STREAM_VIDEO:{
asf_stream_video_format video_format_object;
asf_stream_video video_object;
guint16 vsize;
if (!gst_asf_demux_get_stream_video (&video_object, &data, &size))
goto not_enough_data;
vsize = video_object.size - 40; /* Byte order gets offset by single byte */
GST_INFO ("object is a video stream with %u bytes of "
"additional data", vsize);
if (!gst_asf_demux_get_stream_video_format (&video_format_object,
&data, &size)) {
goto not_enough_data;
}
stream = gst_asf_demux_add_video_stream (demux, &video_format_object,
stream_id, &data, &size);
break;
}
default:
GST_WARNING_OBJECT (demux, "Unknown stream type for stream %u",
stream_id);
demux->other_streams =
g_slist_append (demux->other_streams, GINT_TO_POINTER (stream_id));
break;
}
if (stream)
stream->inspect_payload = inspect_payload;
return stream;
not_enough_data:
{
GST_WARNING_OBJECT (demux, "Unexpected end of data parsing stream object");
/* we'll error out later if we found no streams */
return NULL;
}
}
static const gchar *
gst_asf_demux_get_gst_tag_from_tag_name (const gchar * name_utf8)
{
const struct
{
const gchar *asf_name;
const gchar *gst_name;
} tags[] = {
{
"WM/Genre", GST_TAG_GENRE}, {
"WM/AlbumTitle", GST_TAG_ALBUM}, {
"WM/AlbumArtist", GST_TAG_ARTIST}, {
"WM/Picture", GST_TAG_IMAGE}, {
"WM/Track", GST_TAG_TRACK_NUMBER}, {
"WM/TrackNumber", GST_TAG_TRACK_NUMBER}, {
"WM/Year", GST_TAG_DATE_TIME}
/* { "WM/Composer", GST_TAG_COMPOSER } */
};
gsize out;
guint i;
if (name_utf8 == NULL) {
GST_WARNING ("Failed to convert name to UTF8, skipping");
return NULL;
}
out = strlen (name_utf8);
for (i = 0; i < G_N_ELEMENTS (tags); ++i) {
if (strncmp (tags[i].asf_name, name_utf8, out) == 0) {
GST_LOG ("map tagname '%s' -> '%s'", name_utf8, tags[i].gst_name);
return tags[i].gst_name;
}
}
return NULL;
}
/* gst_asf_demux_add_global_tags() takes ownership of taglist! */
static void
gst_asf_demux_add_global_tags (GstASFDemux * demux, GstTagList * taglist)
{
GstTagList *t;
GST_DEBUG_OBJECT (demux, "adding global tags: %" GST_PTR_FORMAT, taglist);
if (taglist == NULL)
return;
if (gst_tag_list_is_empty (taglist)) {
gst_tag_list_unref (taglist);
return;
}
t = gst_tag_list_merge (demux->taglist, taglist, GST_TAG_MERGE_APPEND);
gst_tag_list_set_scope (t, GST_TAG_SCOPE_GLOBAL);
if (demux->taglist)
gst_tag_list_unref (demux->taglist);
gst_tag_list_unref (taglist);
demux->taglist = t;
GST_LOG_OBJECT (demux, "global tags now: %" GST_PTR_FORMAT, demux->taglist);
}
#define ASF_DEMUX_DATA_TYPE_UTF16LE_STRING 0
#define ASF_DEMUX_DATA_TYPE_BYTE_ARRAY 1
#define ASF_DEMUX_DATA_TYPE_BOOL 2
#define ASF_DEMUX_DATA_TYPE_DWORD 3
static void
asf_demux_parse_picture_tag (GstTagList * tags, const guint8 * tag_data,
guint tag_data_len)
{
GstByteReader r;
const guint8 *img_data = NULL;
guint32 img_data_len = 0;
guint8 pic_type = 0;
gst_byte_reader_init (&r, tag_data, tag_data_len);
/* skip mime type string (we don't trust it and do our own typefinding),
* and also skip the description string, since we don't use it */
if (!gst_byte_reader_get_uint8 (&r, &pic_type) ||
!gst_byte_reader_get_uint32_le (&r, &img_data_len) ||
!gst_byte_reader_skip_string_utf16 (&r) ||
!gst_byte_reader_skip_string_utf16 (&r) ||
!gst_byte_reader_get_data (&r, img_data_len, &img_data)) {
goto not_enough_data;
}
if (!gst_tag_list_add_id3_image (tags, img_data, img_data_len, pic_type))
GST_DEBUG ("failed to add image extracted from WM/Picture tag to taglist");
return;
not_enough_data:
{
GST_DEBUG ("Failed to read WM/Picture tag: not enough data");
GST_MEMDUMP ("WM/Picture data", tag_data, tag_data_len);
return;
}
}
/* Extended Content Description Object */
static GstFlowReturn
gst_asf_demux_process_ext_content_desc (GstASFDemux * demux, guint8 * data,
guint64 size)
{
/* Other known (and unused) 'text/unicode' metadata available :
*
* WM/Lyrics =
* WM/MediaPrimaryClassID = {D1607DBC-E323-4BE2-86A1-48A42A28441E}
* WMFSDKVersion = 9.00.00.2980
* WMFSDKNeeded = 0.0.0.0000
* WM/UniqueFileIdentifier = AMGa_id=R 15334;AMGp_id=P 5149;AMGt_id=T 2324984
* WM/Publisher = 4AD
* WM/Provider = AMG
* WM/ProviderRating = 8
* WM/ProviderStyle = Rock (similar to WM/Genre)
* WM/GenreID (similar to WM/Genre)
* WM/TrackNumber (same as WM/Track but as a string)
*
* Other known (and unused) 'non-text' metadata available :
*
* WM/EncodingTime
* WM/MCDI
* IsVBR
*
* We might want to read WM/TrackNumber and use atoi() if we don't have
* WM/Track
*/
GstTagList *taglist;
guint16 blockcount, i;
gboolean content3D = FALSE;
struct
{
const gchar *interleave_name;
GstASF3DMode interleaving_type;
} stereoscopic_layout_map[] = {
{
"SideBySideRF", GST_ASF_3D_SIDE_BY_SIDE_HALF_RL}, {
"SideBySideLF", GST_ASF_3D_SIDE_BY_SIDE_HALF_LR}, {
"OverUnderRT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL}, {
"OverUnderLT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR}, {
"DualStream", GST_ASF_3D_DUAL_STREAM}
};
GST_INFO_OBJECT (demux, "object is an extended content description");
taglist = gst_tag_list_new_empty ();
/* Content Descriptor Count */
if (size < 2)
goto not_enough_data;
blockcount = gst_asf_demux_get_uint16 (&data, &size);
for (i = 1; i <= blockcount; ++i) {
const gchar *gst_tag_name;
guint16 datatype;
guint16 value_len;
guint16 name_len;
GValue tag_value = { 0, };
gsize in, out;
gchar *name;
gchar *name_utf8 = NULL;
gchar *value;
/* Descriptor */
if (!gst_asf_demux_get_string (&name, &name_len, &data, &size))
goto not_enough_data;
if (size < 2) {
g_free (name);
goto not_enough_data;
}
/* Descriptor Value Data Type */
datatype = gst_asf_demux_get_uint16 (&data, &size);
/* Descriptor Value (not really a string, but same thing reading-wise) */
if (!gst_asf_demux_get_string (&value, &value_len, &data, &size)) {
g_free (name);
goto not_enough_data;
}
name_utf8 =
g_convert (name, name_len, "UTF-8", "UTF-16LE", &in, &out, NULL);
if (name_utf8 != NULL) {
GST_DEBUG ("Found tag/metadata %s", name_utf8);
gst_tag_name = gst_asf_demux_get_gst_tag_from_tag_name (name_utf8);
GST_DEBUG ("gst_tag_name %s", GST_STR_NULL (gst_tag_name));
switch (datatype) {
case ASF_DEMUX_DATA_TYPE_UTF16LE_STRING:{
gchar *value_utf8;
value_utf8 = g_convert (value, value_len, "UTF-8", "UTF-16LE",
&in, &out, NULL);
/* get rid of tags with empty value */
if (value_utf8 != NULL && *value_utf8 != '\0') {
GST_DEBUG ("string value %s", value_utf8);
value_utf8[out] = '\0';
if (gst_tag_name != NULL) {
if (strcmp (gst_tag_name, GST_TAG_DATE_TIME) == 0) {
guint year = atoi (value_utf8);
if (year > 0) {
g_value_init (&tag_value, GST_TYPE_DATE_TIME);
g_value_take_boxed (&tag_value, gst_date_time_new_y (year));
}
} else if (strcmp (gst_tag_name, GST_TAG_GENRE) == 0) {
guint id3v1_genre_id;
const gchar *genre_str;
if (sscanf (value_utf8, "(%u)", &id3v1_genre_id) == 1 &&
((genre_str = gst_tag_id3_genre_get (id3v1_genre_id)))) {
GST_DEBUG ("Genre: %s -> %s", value_utf8, genre_str);
g_free (value_utf8);
value_utf8 = g_strdup (genre_str);
}
} else {
GType tag_type;
/* convert tag from string to other type if required */
tag_type = gst_tag_get_type (gst_tag_name);
g_value_init (&tag_value, tag_type);
if (!gst_value_deserialize (&tag_value, value_utf8)) {
GValue from_val = { 0, };
g_value_init (&from_val, G_TYPE_STRING);
g_value_set_string (&from_val, value_utf8);
if (!g_value_transform (&from_val, &tag_value)) {
GST_WARNING_OBJECT (demux,
"Could not transform string tag to " "%s tag type %s",
gst_tag_name, g_type_name (tag_type));
g_value_unset (&tag_value);
}
g_value_unset (&from_val);
}
}
} else {
/* metadata ! */
GST_DEBUG ("Setting metadata");
g_value_init (&tag_value, G_TYPE_STRING);
g_value_set_string (&tag_value, value_utf8);
/* If we found a stereoscopic marker, look for StereoscopicLayout
* metadata */
if (content3D) {
guint i;
if (strncmp ("StereoscopicLayout", name_utf8,
strlen (name_utf8)) == 0) {
for (i = 0; i < G_N_ELEMENTS (stereoscopic_layout_map); i++) {
if (g_str_equal (stereoscopic_layout_map[i].interleave_name,
value_utf8)) {
demux->asf_3D_mode =
stereoscopic_layout_map[i].interleaving_type;
GST_INFO ("find interleave type %u", demux->asf_3D_mode);
}
}
}
GST_INFO_OBJECT (demux, "3d type is %u", demux->asf_3D_mode);
} else {
demux->asf_3D_mode = GST_ASF_3D_NONE;
GST_INFO_OBJECT (demux, "None 3d type");
}
}
} else if (value_utf8 == NULL) {
GST_WARNING ("Failed to convert string value to UTF8, skipping");
} else {
GST_DEBUG ("Skipping empty string value for %s",
GST_STR_NULL (gst_tag_name));
}
g_free (value_utf8);
break;
}
case ASF_DEMUX_DATA_TYPE_BYTE_ARRAY:{
if (gst_tag_name) {
if (!g_str_equal (gst_tag_name, GST_TAG_IMAGE)) {
GST_FIXME ("Unhandled byte array tag %s",
GST_STR_NULL (gst_tag_name));
break;
} else {
asf_demux_parse_picture_tag (taglist, (guint8 *) value,
value_len);
}
}
break;
}
case ASF_DEMUX_DATA_TYPE_DWORD:{
guint uint_val;
if (value_len < 4)
break;
uint_val = GST_READ_UINT32_LE (value);
/* this is the track number */
g_value_init (&tag_value, G_TYPE_UINT);
/* WM/Track counts from 0 */
if (!strcmp (name_utf8, "WM/Track"))
++uint_val;
g_value_set_uint (&tag_value, uint_val);
break;
}
/* Detect 3D */
case ASF_DEMUX_DATA_TYPE_BOOL:{
gboolean bool_val;
if (value_len < 4)
break;
bool_val = GST_READ_UINT32_LE (value);
if (strncmp ("Stereoscopic", name_utf8, strlen (name_utf8)) == 0) {
if (bool_val) {
GST_INFO_OBJECT (demux, "This is 3D contents");
content3D = TRUE;
} else {
GST_INFO_OBJECT (demux, "This is not 3D contenst");
content3D = FALSE;
}
}
break;
}
default:{
GST_DEBUG ("Skipping tag %s of type %d", gst_tag_name, datatype);
break;
}
}
if (G_IS_VALUE (&tag_value)) {
if (gst_tag_name) {
GstTagMergeMode merge_mode = GST_TAG_MERGE_APPEND;
/* WM/TrackNumber is more reliable than WM/Track, since the latter
* is supposed to have a 0 base but is often wrongly written to start
* from 1 as well, so prefer WM/TrackNumber when we have it: either
* replace the value added earlier from WM/Track or put it first in
* the list, so that it will get picked up by _get_uint() */
if (strcmp (name_utf8, "WM/TrackNumber") == 0)
merge_mode = GST_TAG_MERGE_REPLACE;
gst_tag_list_add_values (taglist, merge_mode, gst_tag_name,
&tag_value, NULL);
} else {
GST_DEBUG ("Setting global metadata %s", name_utf8);
gst_structure_set_value (demux->global_metadata, name_utf8,
&tag_value);
}
g_value_unset (&tag_value);
}
}
g_free (name);
g_free (value);
g_free (name_utf8);
}
gst_asf_demux_add_global_tags (demux, taglist);
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING ("Unexpected end of data parsing ext content desc object");
gst_tag_list_unref (taglist);
return GST_FLOW_OK; /* not really fatal */
}
}
static GstStructure *
gst_asf_demux_get_metadata_for_stream (GstASFDemux * demux, guint stream_num)
{
gchar sname[32];
guint i;
g_snprintf (sname, sizeof (sname), "stream-%u", stream_num);
for (i = 0; i < gst_caps_get_size (demux->metadata); ++i) {
GstStructure *s;
s = gst_caps_get_structure (demux->metadata, i);
if (gst_structure_has_name (s, sname))
return s;
}
gst_caps_append_structure (demux->metadata, gst_structure_new_empty (sname));
/* try lookup again; demux->metadata took ownership of the structure, so we
* can't really make any assumptions about what happened to it, so we can't
* just return it directly after appending it */
return gst_asf_demux_get_metadata_for_stream (demux, stream_num);
}
static GstFlowReturn
gst_asf_demux_process_metadata (GstASFDemux * demux, guint8 * data,
guint64 size)
{
guint16 blockcount, i;
GST_INFO_OBJECT (demux, "object is a metadata object");
/* Content Descriptor Count */
if (size < 2)
goto not_enough_data;
blockcount = gst_asf_demux_get_uint16 (&data, &size);
for (i = 0; i < blockcount; ++i) {
GstStructure *s;
guint16 stream_num, name_len, data_type, lang_idx G_GNUC_UNUSED;
guint32 data_len, ival;
gchar *name_utf8;
if (size < (2 + 2 + 2 + 2 + 4))
goto not_enough_data;
lang_idx = gst_asf_demux_get_uint16 (&data, &size);
stream_num = gst_asf_demux_get_uint16 (&data, &size);
name_len = gst_asf_demux_get_uint16 (&data, &size);
data_type = gst_asf_demux_get_uint16 (&data, &size);
data_len = gst_asf_demux_get_uint32 (&data, &size);
if (size < name_len + data_len)
goto not_enough_data;
/* convert name to UTF-8 */
name_utf8 = g_convert ((gchar *) data, name_len, "UTF-8", "UTF-16LE",
NULL, NULL, NULL);
gst_asf_demux_skip_bytes (name_len, &data, &size);
if (name_utf8 == NULL) {
GST_WARNING ("Failed to convert value name to UTF8, skipping");
gst_asf_demux_skip_bytes (data_len, &data, &size);
continue;
}
if (data_type != ASF_DEMUX_DATA_TYPE_DWORD) {
gst_asf_demux_skip_bytes (data_len, &data, &size);
g_free (name_utf8);
continue;
}
/* read DWORD */
if (size < 4) {
g_free (name_utf8);
goto not_enough_data;
}
ival = gst_asf_demux_get_uint32 (&data, &size);
/* skip anything else there may be, just in case */
gst_asf_demux_skip_bytes (data_len - 4, &data, &size);
s = gst_asf_demux_get_metadata_for_stream (demux, stream_num);
gst_structure_set (s, name_utf8, G_TYPE_INT, ival, NULL);
g_free (name_utf8);
}
GST_INFO_OBJECT (demux, "metadata = %" GST_PTR_FORMAT, demux->metadata);
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING ("Unexpected end of data parsing metadata object");
return GST_FLOW_OK; /* not really fatal */
}
}
static GstFlowReturn
gst_asf_demux_process_header (GstASFDemux * demux, guint8 * data, guint64 size)
{
GstFlowReturn ret = GST_FLOW_OK;
guint32 i, num_objects;
guint8 unknown G_GNUC_UNUSED;
/* Get the rest of the header's header */
if (size < (4 + 1 + 1))
goto not_enough_data;
num_objects = gst_asf_demux_get_uint32 (&data, &size);
unknown = gst_asf_demux_get_uint8 (&data, &size);
unknown = gst_asf_demux_get_uint8 (&data, &size);
GST_INFO_OBJECT (demux, "object is a header with %u parts", num_objects);
demux->saw_file_header = FALSE;
/* Loop through the header's objects, processing those */
for (i = 0; i < num_objects; ++i) {
GST_INFO_OBJECT (demux, "reading header part %u", i);
ret = gst_asf_demux_process_object (demux, &data, &size);
if (ret != GST_FLOW_OK) {
GST_WARNING ("process_object returned %s", gst_asf_get_flow_name (ret));
break;
}
}
if (!demux->saw_file_header) {
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("Header does not have mandatory FILE section"));
return GST_FLOW_ERROR;
}
return ret;
not_enough_data:
{
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("short read parsing HEADER object"));
return GST_FLOW_ERROR;
}
}
static GstFlowReturn
gst_asf_demux_process_file (GstASFDemux * demux, guint8 * data, guint64 size)
{
guint64 creation_time G_GNUC_UNUSED;
guint64 file_size G_GNUC_UNUSED;
guint64 send_time G_GNUC_UNUSED;
guint64 packets_count, play_time, preroll;
guint32 flags, min_pktsize, max_pktsize, min_bitrate G_GNUC_UNUSED;
if (size < (16 + 8 + 8 + 8 + 8 + 8 + 8 + 4 + 4 + 4 + 4))
goto not_enough_data;
gst_asf_demux_skip_bytes (16, &data, &size); /* skip GUID */
file_size = gst_asf_demux_get_uint64 (&data, &size);
creation_time = gst_asf_demux_get_uint64 (&data, &size);
packets_count = gst_asf_demux_get_uint64 (&data, &size);
play_time = gst_asf_demux_get_uint64 (&data, &size);
send_time = gst_asf_demux_get_uint64 (&data, &size);
preroll = gst_asf_demux_get_uint64 (&data, &size);
flags = gst_asf_demux_get_uint32 (&data, &size);
min_pktsize = gst_asf_demux_get_uint32 (&data, &size);
max_pktsize = gst_asf_demux_get_uint32 (&data, &size);
min_bitrate = gst_asf_demux_get_uint32 (&data, &size);
demux->broadcast = ! !(flags & 0x01);
demux->seekable = ! !(flags & 0x02);
GST_DEBUG_OBJECT (demux, "min_pktsize = %u", min_pktsize);
GST_DEBUG_OBJECT (demux, "flags::broadcast = %d", demux->broadcast);
GST_DEBUG_OBJECT (demux, "flags::seekable = %d", demux->seekable);
if (demux->broadcast) {
/* these fields are invalid if the broadcast flag is set */
play_time = 0;
file_size = 0;
}
if (min_pktsize != max_pktsize)
goto non_fixed_packet_size;
demux->packet_size = max_pktsize;
/* FIXME: do we need send_time as well? what is it? */
if ((play_time * 100) >= (preroll * GST_MSECOND))
demux->play_time = (play_time * 100) - (preroll * GST_MSECOND);
else
demux->play_time = 0;
demux->preroll = preroll * GST_MSECOND;
/* initial latency */
demux->latency = demux->preroll;
if (demux->play_time == 0)
demux->seekable = FALSE;
GST_DEBUG_OBJECT (demux, "play_time %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->play_time));
GST_DEBUG_OBJECT (demux, "preroll %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->preroll));
if (demux->play_time > 0) {
demux->segment.duration = demux->play_time;
}
GST_INFO ("object is a file with %" G_GUINT64_FORMAT " data packets",
packets_count);
GST_INFO ("preroll = %" G_GUINT64_FORMAT, demux->preroll);
demux->saw_file_header = TRUE;
return GST_FLOW_OK;
/* ERRORS */
non_fixed_packet_size:
{
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("packet size must be fixed"));
return GST_FLOW_ERROR;
}
not_enough_data:
{
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("short read parsing FILE object"));
return GST_FLOW_ERROR;
}
}
/* Content Description Object */
static GstFlowReturn
gst_asf_demux_process_comment (GstASFDemux * demux, guint8 * data, guint64 size)
{
struct
{
const gchar *gst_tag;
guint16 val_length;
gchar *val_utf8;
} tags[5] = {
{
GST_TAG_TITLE, 0, NULL}, {
GST_TAG_ARTIST, 0, NULL}, {
GST_TAG_COPYRIGHT, 0, NULL}, {
GST_TAG_DESCRIPTION, 0, NULL}, {
GST_TAG_COMMENT, 0, NULL}
};
GstTagList *taglist;
GValue value = { 0 };
gsize in, out;
gint i = -1;
GST_INFO_OBJECT (demux, "object is a comment");
if (size < (2 + 2 + 2 + 2 + 2))
goto not_enough_data;
tags[0].val_length = gst_asf_demux_get_uint16 (&data, &size);
tags[1].val_length = gst_asf_demux_get_uint16 (&data, &size);
tags[2].val_length = gst_asf_demux_get_uint16 (&data, &size);
tags[3].val_length = gst_asf_demux_get_uint16 (&data, &size);
tags[4].val_length = gst_asf_demux_get_uint16 (&data, &size);
GST_DEBUG_OBJECT (demux, "Comment lengths: title=%d author=%d copyright=%d "
"description=%d rating=%d", tags[0].val_length, tags[1].val_length,
tags[2].val_length, tags[3].val_length, tags[4].val_length);
for (i = 0; i < G_N_ELEMENTS (tags); ++i) {
if (size < tags[i].val_length)
goto not_enough_data;
/* might be just '/0', '/0'... */
if (tags[i].val_length > 2 && tags[i].val_length % 2 == 0) {
/* convert to UTF-8 */
tags[i].val_utf8 = g_convert ((gchar *) data, tags[i].val_length,
"UTF-8", "UTF-16LE", &in, &out, NULL);
}
gst_asf_demux_skip_bytes (tags[i].val_length, &data, &size);
}
/* parse metadata into taglist */
taglist = gst_tag_list_new_empty ();
g_value_init (&value, G_TYPE_STRING);
for (i = 0; i < G_N_ELEMENTS (tags); ++i) {
if (tags[i].val_utf8 && strlen (tags[i].val_utf8) > 0 && tags[i].gst_tag) {
g_value_set_string (&value, tags[i].val_utf8);
gst_tag_list_add_values (taglist, GST_TAG_MERGE_APPEND,
tags[i].gst_tag, &value, NULL);
}
}
g_value_unset (&value);
gst_asf_demux_add_global_tags (demux, taglist);
for (i = 0; i < G_N_ELEMENTS (tags); ++i)
g_free (tags[i].val_utf8);
return GST_FLOW_OK;
not_enough_data:
{
GST_WARNING_OBJECT (demux, "unexpectedly short of data while processing "
"comment tag section %d, skipping comment object", i);
for (i = 0; i < G_N_ELEMENTS (tags); i++)
g_free (tags[i].val_utf8);
return GST_FLOW_OK; /* not really fatal */
}
}
static GstFlowReturn
gst_asf_demux_process_bitrate_props_object (GstASFDemux * demux, guint8 * data,
guint64 size)
{
guint16 num_streams, i;
AsfStream *stream;
if (size < 2)
goto not_enough_data;
num_streams = gst_asf_demux_get_uint16 (&data, &size);
GST_INFO ("object is a bitrate properties object with %u streams",
num_streams);
if (size < (num_streams * (2 + 4)))
goto not_enough_data;
for (i = 0; i < num_streams; ++i) {
guint32 bitrate;
guint16 stream_id;
stream_id = gst_asf_demux_get_uint16 (&data, &size);
bitrate = gst_asf_demux_get_uint32 (&data, &size);
if (stream_id < GST_ASF_DEMUX_NUM_STREAM_IDS) {
GST_DEBUG_OBJECT (demux, "bitrate of stream %u = %u", stream_id, bitrate);
stream = gst_asf_demux_get_stream (demux, stream_id);
if (stream) {
if (stream->pending_tags == NULL)
stream->pending_tags = gst_tag_list_new_empty ();
gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_REPLACE,
GST_TAG_BITRATE, bitrate, NULL);
} else {
GST_WARNING_OBJECT (demux, "Stream id %u wasn't found", stream_id);
}
} else {
GST_WARNING ("stream id %u is too large", stream_id);
}
}
return GST_FLOW_OK;
not_enough_data:
{
GST_WARNING_OBJECT (demux, "short read parsing bitrate props object!");
return GST_FLOW_OK; /* not really fatal */
}
}
static GstFlowReturn
gst_asf_demux_process_header_ext (GstASFDemux * demux, guint8 * data,
guint64 size)
{
GstFlowReturn ret = GST_FLOW_OK;
guint64 hdr_size;
/* Get the rest of the header's header */
if (size < (16 + 2 + 4))
goto not_enough_data;
/* skip GUID and two other bytes */
gst_asf_demux_skip_bytes (16 + 2, &data, &size);
hdr_size = gst_asf_demux_get_uint32 (&data, &size);
GST_INFO ("extended header object with a size of %u bytes", (guint) size);
/* FIXME: does data_size include the rest of the header that we have read? */
if (hdr_size > size)
goto not_enough_data;
while (hdr_size > 0) {
ret = gst_asf_demux_process_object (demux, &data, &hdr_size);
if (ret != GST_FLOW_OK)
break;
}
return ret;
not_enough_data:
{
GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL),
("short read parsing extended header object"));
return GST_FLOW_ERROR;
}
}
static GstFlowReturn
gst_asf_demux_process_language_list (GstASFDemux * demux, guint8 * data,
guint64 size)
{
guint i;
if (size < 2)
goto not_enough_data;
if (demux->languages) {
GST_WARNING ("More than one LANGUAGE_LIST object in stream");
g_strfreev (demux->languages);
demux->languages = NULL;
demux->num_languages = 0;
}
demux->num_languages = gst_asf_demux_get_uint16 (&data, &size);
GST_LOG ("%u languages:", demux->num_languages);
demux->languages = g_new0 (gchar *, demux->num_languages + 1);
for (i = 0; i < demux->num_languages; ++i) {
guint8 len, *lang_data = NULL;
if (size < 1)
goto not_enough_data;
len = gst_asf_demux_get_uint8 (&data, &size);
if (gst_asf_demux_get_bytes (&lang_data, len, &data, &size)) {
gchar *utf8;
utf8 = g_convert ((gchar *) lang_data, len, "UTF-8", "UTF-16LE", NULL,
NULL, NULL);
/* truncate "en-us" etc. to just "en" */
if (utf8 && strlen (utf8) >= 5 && (utf8[2] == '-' || utf8[2] == '_')) {
utf8[2] = '\0';
}
GST_DEBUG ("[%u] %s", i, GST_STR_NULL (utf8));
demux->languages[i] = utf8;
g_free (lang_data);
} else {
goto not_enough_data;
}
}
return GST_FLOW_OK;
not_enough_data:
{
GST_WARNING_OBJECT (demux, "short read parsing language list object!");
g_free (demux->languages);
demux->languages = NULL;
demux->num_languages = 0;
return GST_FLOW_OK; /* not fatal */
}
}
static GstFlowReturn
gst_asf_demux_process_simple_index (GstASFDemux * demux, guint8 * data,
guint64 size)
{
GstClockTime interval;
guint32 count, i;
if (size < (16 + 8 + 4 + 4))
goto not_enough_data;
/* skip file id */
gst_asf_demux_skip_bytes (16, &data, &size);
interval = gst_asf_demux_get_uint64 (&data, &size) * (GstClockTime) 100;
gst_asf_demux_skip_bytes (4, &data, &size);
count = gst_asf_demux_get_uint32 (&data, &size);
if (count > 0) {
demux->sidx_interval = interval;
demux->sidx_num_entries = count;
g_free (demux->sidx_entries);
demux->sidx_entries = g_new0 (AsfSimpleIndexEntry, count);
for (i = 0; i < count; ++i) {
if (G_UNLIKELY (size < 6)) {
/* adjust for broken files, to avoid having entries at the end
* of the parsed index that point to time=0. Resulting in seeking to
* the end of the file leading back to the beginning */
demux->sidx_num_entries -= (count - i);
break;
}
demux->sidx_entries[i].packet = gst_asf_demux_get_uint32 (&data, &size);
demux->sidx_entries[i].count = gst_asf_demux_get_uint16 (&data, &size);
GST_LOG_OBJECT (demux, "%" GST_TIME_FORMAT " = packet %4u count : %2d",
GST_TIME_ARGS (i * interval), demux->sidx_entries[i].packet,
demux->sidx_entries[i].count);
}
} else {
GST_DEBUG_OBJECT (demux, "simple index object with 0 entries");
}
return GST_FLOW_OK;
not_enough_data:
{
GST_WARNING_OBJECT (demux, "short read parsing simple index object!");
return GST_FLOW_OK; /* not fatal */
}
}
static GstFlowReturn
gst_asf_demux_process_advanced_mutual_exclusion (GstASFDemux * demux,
guint8 * data, guint64 size)
{
ASFGuid guid;
guint16 num, i;
if (size < 16 + 2 + (2 * 2))
goto not_enough_data;
gst_asf_demux_get_guid (&guid, &data, &size);
num = gst_asf_demux_get_uint16 (&data, &size);
if (num < 2) {
GST_WARNING_OBJECT (demux, "nonsensical mutually exclusive streams count");
return GST_FLOW_OK;
}
if (size < (num * sizeof (guint16)))
goto not_enough_data;
/* read mutually exclusive stream numbers */
for (i = 0; i < num; ++i) {
guint8 mes;
mes = gst_asf_demux_get_uint16 (&data, &size) & 0x7f;
GST_LOG_OBJECT (demux, "mutually exclusive: stream %d", mes);
demux->mut_ex_streams =
g_slist_append (demux->mut_ex_streams, GINT_TO_POINTER (mes));
}
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING_OBJECT (demux, "short read parsing advanced mutual exclusion");
return GST_FLOW_OK; /* not absolutely fatal */
}
}
gboolean
gst_asf_demux_is_unknown_stream (GstASFDemux * demux, guint stream_num)
{
return g_slist_find (demux->other_streams,
GINT_TO_POINTER (stream_num)) == NULL;
}
static GstFlowReturn
gst_asf_demux_process_ext_stream_props (GstASFDemux * demux, guint8 * data,
guint64 size)
{
AsfStreamExtProps esp;
AsfStream *stream = NULL;
AsfObject stream_obj;
guint16 stream_name_count;
guint16 num_payload_ext;
guint64 len;
guint8 *stream_obj_data = NULL;
guint8 *data_start;
guint obj_size;
guint i, stream_num;
data_start = data;
obj_size = (guint) size;
esp.payload_extensions = NULL;
if (size < 64)
goto not_enough_data;
esp.valid = TRUE;
esp.start_time = gst_asf_demux_get_uint64 (&data, &size) * GST_MSECOND;
esp.end_time = gst_asf_demux_get_uint64 (&data, &size) * GST_MSECOND;
esp.data_bitrate = gst_asf_demux_get_uint32 (&data, &size);
esp.buffer_size = gst_asf_demux_get_uint32 (&data, &size);
esp.intial_buf_fullness = gst_asf_demux_get_uint32 (&data, &size);
esp.data_bitrate2 = gst_asf_demux_get_uint32 (&data, &size);
esp.buffer_size2 = gst_asf_demux_get_uint32 (&data, &size);
esp.intial_buf_fullness2 = gst_asf_demux_get_uint32 (&data, &size);
esp.max_obj_size = gst_asf_demux_get_uint32 (&data, &size);
esp.flags = gst_asf_demux_get_uint32 (&data, &size);
stream_num = gst_asf_demux_get_uint16 (&data, &size);
esp.lang_idx = gst_asf_demux_get_uint16 (&data, &size);
esp.avg_time_per_frame = gst_asf_demux_get_uint64 (&data, &size);
stream_name_count = gst_asf_demux_get_uint16 (&data, &size);
num_payload_ext = gst_asf_demux_get_uint16 (&data, &size);
GST_INFO ("start_time = %" GST_TIME_FORMAT,
GST_TIME_ARGS (esp.start_time));
GST_INFO ("end_time = %" GST_TIME_FORMAT,
GST_TIME_ARGS (esp.end_time));
GST_INFO ("flags = %08x", esp.flags);
GST_INFO ("average time per frame = %" GST_TIME_FORMAT,
GST_TIME_ARGS (esp.avg_time_per_frame * 100));
GST_INFO ("stream number = %u", stream_num);
GST_INFO ("stream language ID idx = %u (%s)", esp.lang_idx,
(esp.lang_idx < demux->num_languages) ?
GST_STR_NULL (demux->languages[esp.lang_idx]) : "??");
GST_INFO ("stream name count = %u", stream_name_count);
/* read stream names */
for (i = 0; i < stream_name_count; ++i) {
guint16 stream_lang_idx G_GNUC_UNUSED;
gchar *stream_name = NULL;
if (size < 2)
goto not_enough_data;
stream_lang_idx = gst_asf_demux_get_uint16 (&data, &size);
if (!gst_asf_demux_get_string (&stream_name, NULL, &data, &size))
goto not_enough_data;
GST_INFO ("stream name %d: %s", i, GST_STR_NULL (stream_name));
g_free (stream_name); /* TODO: store names in struct */
}
/* read payload extension systems stuff */
GST_LOG ("payload extension systems count = %u", num_payload_ext);
if (num_payload_ext > 0)
esp.payload_extensions = g_new0 (AsfPayloadExtension, num_payload_ext + 1);
for (i = 0; i < num_payload_ext; ++i) {
AsfPayloadExtension ext;
ASFGuid ext_guid;
guint32 sys_info_len;
if (size < 16 + 2 + 4)
goto not_enough_data;
gst_asf_demux_get_guid (&ext_guid, &data, &size);
ext.id = gst_asf_demux_identify_guid (asf_payload_ext_guids, &ext_guid);
ext.len = gst_asf_demux_get_uint16 (&data, &size);
sys_info_len = gst_asf_demux_get_uint32 (&data, &size);
GST_LOG ("payload systems info len = %u", sys_info_len);
if (!gst_asf_demux_skip_bytes (sys_info_len, &data, &size))
goto not_enough_data;
esp.payload_extensions[i] = ext;
}
GST_LOG ("bytes read: %u/%u", (guint) (data - data_start), obj_size);
/* there might be an optional STREAM_INFO object here now; if not, we
* should have parsed the corresponding stream info object already (since
* we are parsing the extended stream properties objects delayed) */
if (size == 0) {
stream = gst_asf_demux_get_stream (demux, stream_num);
goto done;
}
if (size < ASF_OBJECT_HEADER_SIZE)
goto not_enough_data;
/* get size of the stream object */
if (!asf_demux_peek_object (demux, data, size, &stream_obj, TRUE))
goto corrupted_stream;
if (stream_obj.id != ASF_OBJ_STREAM)
goto expected_stream_object;
if (stream_obj.size < ASF_OBJECT_HEADER_SIZE ||
stream_obj.size > (10 * 1024 * 1024))
goto not_enough_data;
gst_asf_demux_skip_bytes (ASF_OBJECT_HEADER_SIZE, &data, &size);
/* process this stream object later after all the other 'normal' ones
* have been processed (since the others are more important/non-hidden) */
len = stream_obj.size - ASF_OBJECT_HEADER_SIZE;
if (!gst_asf_demux_get_bytes (&stream_obj_data, len, &data, &size))
goto not_enough_data;
/* parse stream object */
stream = gst_asf_demux_parse_stream_object (demux, stream_obj_data, len);
g_free (stream_obj_data);
done:
if (stream) {
stream->ext_props = esp;
/* try to set the framerate */
if (stream->is_video && stream->caps) {
GValue framerate = { 0 };
GstStructure *s;
gint num, denom;
g_value_init (&framerate, GST_TYPE_FRACTION);
num = GST_SECOND / 100;
denom = esp.avg_time_per_frame;
if (denom == 0) {
/* avoid division by 0, assume 25/1 framerate */
denom = GST_SECOND / 2500;
}
gst_value_set_fraction (&framerate, num, denom);
stream->caps = gst_caps_make_writable (stream->caps);
s = gst_caps_get_structure (stream->caps, 0);
gst_structure_set_value (s, "framerate", &framerate);
g_value_unset (&framerate);
GST_DEBUG_OBJECT (demux, "setting framerate of %d/%d = %f",
num, denom, ((gdouble) num) / denom);
}
/* add language info now if we have it */
if (stream->ext_props.lang_idx < demux->num_languages) {
if (stream->pending_tags == NULL)
stream->pending_tags = gst_tag_list_new_empty ();
GST_LOG_OBJECT (demux, "stream %u has language '%s'", stream->id,
demux->languages[stream->ext_props.lang_idx]);
gst_tag_list_add (stream->pending_tags, GST_TAG_MERGE_APPEND,
GST_TAG_LANGUAGE_CODE, demux->languages[stream->ext_props.lang_idx],
NULL);
}
} else if (gst_asf_demux_is_unknown_stream (demux, stream_num)) {
GST_WARNING_OBJECT (demux, "Ext. stream properties for unknown stream");
}
if (!stream)
g_free (esp.payload_extensions);
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING_OBJECT (demux, "short read parsing ext stream props object!");
g_free (esp.payload_extensions);
return GST_FLOW_OK; /* not absolutely fatal */
}
expected_stream_object:
{
GST_WARNING_OBJECT (demux, "error parsing extended stream properties "
"object: expected embedded stream object, but got %s object instead!",
gst_asf_get_guid_nick (asf_object_guids, stream_obj.id));
g_free (esp.payload_extensions);
return GST_FLOW_OK; /* not absolutely fatal */
}
corrupted_stream:
{
GST_WARNING_OBJECT (demux, "Corrupted stream");
g_free (esp.payload_extensions);
return GST_FLOW_ERROR;
}
}
static const gchar *
gst_asf_demux_push_obj (GstASFDemux * demux, guint32 obj_id)
{
const gchar *nick;
nick = gst_asf_get_guid_nick (asf_object_guids, obj_id);
if (g_str_has_prefix (nick, "ASF_OBJ_"))
nick += strlen ("ASF_OBJ_");
if (demux->objpath == NULL) {
demux->objpath = g_strdup (nick);
} else {
gchar *newpath;
newpath = g_strdup_printf ("%s/%s", demux->objpath, nick);
g_free (demux->objpath);
demux->objpath = newpath;
}
return (const gchar *) demux->objpath;
}
static void
gst_asf_demux_pop_obj (GstASFDemux * demux)
{
gchar *s;
if ((s = g_strrstr (demux->objpath, "/"))) {
*s = '\0';
} else {
g_free (demux->objpath);
demux->objpath = NULL;
}
}
static void
gst_asf_demux_process_queued_extended_stream_objects (GstASFDemux * demux)
{
GSList *l;
guint i;
/* Parse the queued extended stream property objects and add the info
* to the existing streams or add the new embedded streams, but without
* activating them yet */
GST_LOG_OBJECT (demux, "%u queued extended stream properties objects",
g_slist_length (demux->ext_stream_props));
for (l = demux->ext_stream_props, i = 0; l != NULL; l = l->next, ++i) {
GstBuffer *buf = GST_BUFFER (l->data);
GstMapInfo map;
gst_buffer_map (buf, &map, GST_MAP_READ);
GST_LOG_OBJECT (demux, "parsing ext. stream properties object #%u", i);
gst_asf_demux_process_ext_stream_props (demux, map.data, map.size);
gst_buffer_unmap (buf, &map);
gst_buffer_unref (buf);
}
g_slist_free (demux->ext_stream_props);
demux->ext_stream_props = NULL;
}
#if 0
static void
gst_asf_demux_activate_ext_props_streams (GstASFDemux * demux)
{
guint i, j;
for (i = 0; i < demux->num_streams; ++i) {
AsfStream *stream;
gboolean is_hidden;
GSList *x;
stream = &demux->stream[i];
GST_LOG_OBJECT (demux, "checking stream %2u", stream->id);
if (stream->active) {
GST_LOG_OBJECT (demux, "stream %2u is already activated", stream->id);
continue;
}
is_hidden = FALSE;
for (x = demux->mut_ex_streams; x != NULL; x = x->next) {
guint8 *mes;
/* check for each mutual exclusion whether it affects this stream */
for (mes = (guint8 *) x->data; mes != NULL && *mes != 0xff; ++mes) {
if (*mes == stream->id) {
/* if yes, check if we've already added streams that are mutually
* exclusive with the stream we're about to add */
for (mes = (guint8 *) x->data; mes != NULL && *mes != 0xff; ++mes) {
for (j = 0; j < demux->num_streams; ++j) {
/* if the broadcast flag is set, assume the hidden streams aren't
* actually streamed and hide them (or playbin won't work right),
* otherwise assume their data is available */
if (demux->stream[j].id == *mes && demux->broadcast) {
is_hidden = TRUE;
GST_LOG_OBJECT (demux, "broadcast stream ID %d to be added is "
"mutually exclusive with already existing stream ID %d, "
"hiding stream", stream->id, demux->stream[j].id);
goto next;
}
}
}
break;
}
}
}
next:
/* FIXME: we should do stream activation based on preroll data in
* streaming mode too */
if (demux->streaming && !is_hidden)
gst_asf_demux_activate_stream (demux, stream);
}
}
#endif
static GstFlowReturn
gst_asf_demux_process_object (GstASFDemux * demux, guint8 ** p_data,
guint64 * p_size)
{
GstFlowReturn ret = GST_FLOW_OK;
AsfObject obj;
guint64 obj_data_size;
if (*p_size < ASF_OBJECT_HEADER_SIZE)
return ASF_FLOW_NEED_MORE_DATA;
if (!asf_demux_peek_object (demux, *p_data, ASF_OBJECT_HEADER_SIZE, &obj,
TRUE))
return GST_FLOW_ERROR;
gst_asf_demux_skip_bytes (ASF_OBJECT_HEADER_SIZE, p_data, p_size);
obj_data_size = obj.size - ASF_OBJECT_HEADER_SIZE;
if (*p_size < obj_data_size)
return ASF_FLOW_NEED_MORE_DATA;
gst_asf_demux_push_obj (demux, obj.id);
GST_INFO ("%s: size %" G_GUINT64_FORMAT, demux->objpath, obj.size);
switch (obj.id) {
case ASF_OBJ_STREAM:
gst_asf_demux_parse_stream_object (demux, *p_data, obj_data_size);
ret = GST_FLOW_OK;
break;
case ASF_OBJ_FILE:
ret = gst_asf_demux_process_file (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_HEADER:
ret = gst_asf_demux_process_header (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_COMMENT:
ret = gst_asf_demux_process_comment (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_HEAD1:
ret = gst_asf_demux_process_header_ext (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_BITRATE_PROPS:
ret =
gst_asf_demux_process_bitrate_props_object (demux, *p_data,
obj_data_size);
break;
case ASF_OBJ_EXT_CONTENT_DESC:
ret =
gst_asf_demux_process_ext_content_desc (demux, *p_data,
obj_data_size);
break;
case ASF_OBJ_METADATA_OBJECT:
ret = gst_asf_demux_process_metadata (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_EXTENDED_STREAM_PROPS:{
GstBuffer *buf;
/* process these later, we might not have parsed the corresponding
* stream object yet */
GST_LOG ("%s: queued for later parsing", demux->objpath);
buf = gst_buffer_new_and_alloc (obj_data_size);
gst_buffer_fill (buf, 0, *p_data, obj_data_size);
demux->ext_stream_props = g_slist_append (demux->ext_stream_props, buf);
ret = GST_FLOW_OK;
break;
}
case ASF_OBJ_LANGUAGE_LIST:
ret = gst_asf_demux_process_language_list (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_ADVANCED_MUTUAL_EXCLUSION:
ret = gst_asf_demux_process_advanced_mutual_exclusion (demux, *p_data,
obj_data_size);
break;
case ASF_OBJ_SIMPLE_INDEX:
ret = gst_asf_demux_process_simple_index (demux, *p_data, obj_data_size);
break;
case ASF_OBJ_CONTENT_ENCRYPTION:
case ASF_OBJ_EXT_CONTENT_ENCRYPTION:
case ASF_OBJ_DIGITAL_SIGNATURE_OBJECT:
case ASF_OBJ_UNKNOWN_ENCRYPTION_OBJECT:
goto error_encrypted;
case ASF_OBJ_CONCEAL_NONE:
case ASF_OBJ_HEAD2:
case ASF_OBJ_UNDEFINED:
case ASF_OBJ_CODEC_COMMENT:
case ASF_OBJ_INDEX:
case ASF_OBJ_PADDING:
case ASF_OBJ_BITRATE_MUTEX:
case ASF_OBJ_COMPATIBILITY:
case ASF_OBJ_INDEX_PLACEHOLDER:
case ASF_OBJ_INDEX_PARAMETERS:
case ASF_OBJ_STREAM_PRIORITIZATION:
case ASF_OBJ_SCRIPT_COMMAND:
case ASF_OBJ_METADATA_LIBRARY_OBJECT:
default:
/* Unknown/unhandled object, skip it and hope for the best */
GST_INFO ("%s: skipping object", demux->objpath);
ret = GST_FLOW_OK;
break;
}
/* this can't fail, we checked the number of bytes available before */
gst_asf_demux_skip_bytes (obj_data_size, p_data, p_size);
GST_LOG ("%s: ret = %s", demux->objpath, gst_asf_get_flow_name (ret));
gst_asf_demux_pop_obj (demux);
return ret;
/* ERRORS */
error_encrypted:
{
GST_ELEMENT_ERROR (demux, STREAM, DECRYPT, (NULL), (NULL));
return GST_FLOW_ERROR;
}
}
static void
gst_asf_demux_descramble_buffer (GstASFDemux * demux, AsfStream * stream,
GstBuffer ** p_buffer)
{
GstBuffer *descrambled_buffer;
GstBuffer *scrambled_buffer;
GstBuffer *sub_buffer;
guint offset;
guint off;
guint row;
guint col;
guint idx;
/* descrambled_buffer is initialised in the first iteration */
descrambled_buffer = NULL;
scrambled_buffer = *p_buffer;
if (gst_buffer_get_size (scrambled_buffer) <
stream->ds_packet_size * stream->span)
return;
for (offset = 0; offset < gst_buffer_get_size (scrambled_buffer);
offset += stream->ds_chunk_size) {
off = offset / stream->ds_chunk_size;
row = off / stream->span;
col = off % stream->span;
idx = row + col * stream->ds_packet_size / stream->ds_chunk_size;
GST_DEBUG ("idx=%u, row=%u, col=%u, off=%u, ds_chunk_size=%u", idx, row,
col, off, stream->ds_chunk_size);
GST_DEBUG ("scrambled buffer size=%" G_GSIZE_FORMAT
", span=%u, packet_size=%u", gst_buffer_get_size (scrambled_buffer),
stream->span, stream->ds_packet_size);
GST_DEBUG ("gst_buffer_get_size (scrambled_buffer) = %" G_GSIZE_FORMAT,
gst_buffer_get_size (scrambled_buffer));
sub_buffer =
gst_buffer_copy_region (scrambled_buffer, GST_BUFFER_COPY_MEMORY,
idx * stream->ds_chunk_size, stream->ds_chunk_size);
if (!offset) {
descrambled_buffer = sub_buffer;
} else {
descrambled_buffer = gst_buffer_append (descrambled_buffer, sub_buffer);
}
}
GST_BUFFER_TIMESTAMP (descrambled_buffer) =
GST_BUFFER_TIMESTAMP (scrambled_buffer);
GST_BUFFER_DURATION (descrambled_buffer) =
GST_BUFFER_DURATION (scrambled_buffer);
GST_BUFFER_OFFSET (descrambled_buffer) = GST_BUFFER_OFFSET (scrambled_buffer);
GST_BUFFER_OFFSET_END (descrambled_buffer) =
GST_BUFFER_OFFSET_END (scrambled_buffer);
/* FIXME/CHECK: do we need to transfer buffer flags here too? */
gst_buffer_unref (scrambled_buffer);
*p_buffer = descrambled_buffer;
}
static gboolean
gst_asf_demux_element_send_event (GstElement * element, GstEvent * event)
{
GstASFDemux *demux = GST_ASF_DEMUX (element);
gint i;
GST_DEBUG ("handling element event of type %s", GST_EVENT_TYPE_NAME (event));
for (i = 0; i < demux->num_streams; ++i) {
gst_event_ref (event);
if (gst_asf_demux_handle_src_event (demux->stream[i].pad,
GST_OBJECT_CAST (element), event)) {
gst_event_unref (event);
return TRUE;
}
}
gst_event_unref (event);
return FALSE;
}
/* takes ownership of the passed event */
static gboolean
gst_asf_demux_send_event_unlocked (GstASFDemux * demux, GstEvent * event)
{
gboolean ret = TRUE;
gint i;
GST_DEBUG_OBJECT (demux, "sending %s event to all source pads",
GST_EVENT_TYPE_NAME (event));
for (i = 0; i < demux->num_streams; ++i) {
gst_event_ref (event);
ret &= gst_pad_push_event (demux->stream[i].pad, event);
}
gst_event_unref (event);
return ret;
}
static gboolean
gst_asf_demux_handle_src_query (GstPad * pad, GstObject * parent,
GstQuery * query)
{
GstASFDemux *demux;
gboolean res = FALSE;
demux = GST_ASF_DEMUX (parent);
GST_DEBUG ("handling %s query",
gst_query_type_get_name (GST_QUERY_TYPE (query)));
switch (GST_QUERY_TYPE (query)) {
case GST_QUERY_DURATION:
{
GstFormat format;
gst_query_parse_duration (query, &format, NULL);
if (format != GST_FORMAT_TIME) {
GST_LOG ("only support duration queries in TIME format");
break;
}
res = gst_pad_query_default (pad, parent, query);
if (!res) {
GST_OBJECT_LOCK (demux);
if (demux->segment.duration != GST_CLOCK_TIME_NONE) {
GST_LOG ("returning duration: %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->segment.duration));
gst_query_set_duration (query, GST_FORMAT_TIME,
demux->segment.duration);
res = TRUE;
} else {
GST_LOG ("duration not known yet");
}
GST_OBJECT_UNLOCK (demux);
}
break;
}
case GST_QUERY_POSITION:{
GstFormat format;
gst_query_parse_position (query, &format, NULL);
if (format != GST_FORMAT_TIME) {
GST_LOG ("only support position queries in TIME format");
break;
}
GST_OBJECT_LOCK (demux);
if (demux->segment.position != GST_CLOCK_TIME_NONE) {
GST_LOG ("returning position: %" GST_TIME_FORMAT,
GST_TIME_ARGS (demux->segment.position));
gst_query_set_position (query, GST_FORMAT_TIME,
demux->segment.position);
res = TRUE;
} else {
GST_LOG ("position not known yet");
}
GST_OBJECT_UNLOCK (demux);
break;
}
case GST_QUERY_SEEKING:{
GstFormat format;
gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
if (format == GST_FORMAT_TIME) {
gint64 duration;
GST_OBJECT_LOCK (demux);
duration = demux->segment.duration;
GST_OBJECT_UNLOCK (demux);
if (!demux->streaming || !demux->seekable) {
gst_query_set_seeking (query, GST_FORMAT_TIME, demux->seekable, 0,
duration);
res = TRUE;
} else {
GstFormat fmt;
gboolean seekable;
/* try upstream first in TIME */
res = gst_pad_query_default (pad, parent, query);
gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
GST_LOG_OBJECT (demux, "upstream %s seekable %d",
GST_STR_NULL (gst_format_get_name (fmt)), seekable);
/* if no luck, maybe in BYTES */
if (!seekable || fmt != GST_FORMAT_TIME) {
GstQuery *q;
q = gst_query_new_seeking (GST_FORMAT_BYTES);
if ((res = gst_pad_peer_query (demux->sinkpad, q))) {
gst_query_parse_seeking (q, &fmt, &seekable, NULL, NULL);
GST_LOG_OBJECT (demux, "upstream %s seekable %d",
GST_STR_NULL (gst_format_get_name (fmt)), seekable);
if (fmt != GST_FORMAT_BYTES)
seekable = FALSE;
}
gst_query_unref (q);
gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0,
duration);
res = TRUE;
}
}
} else
GST_LOG_OBJECT (demux, "only support seeking in TIME format");
break;
}
case GST_QUERY_LATENCY:
{
gboolean live;
GstClockTime min, max;
/* preroll delay does not matter in non-live pipeline,
* but we might end up in a live (rtsp) one ... */
/* first forward */
res = gst_pad_query_default (pad, parent, query);
if (!res)
break;
gst_query_parse_latency (query, &live, &min, &max);
GST_DEBUG_OBJECT (demux, "Peer latency: live %d, min %"
GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
GST_TIME_ARGS (min), GST_TIME_ARGS (max));
GST_OBJECT_LOCK (demux);
min += demux->latency;
if (max != -1)
max += demux->latency;
GST_OBJECT_UNLOCK (demux);
gst_query_set_latency (query, live, min, max);
break;
}
case GST_QUERY_SEGMENT:
{
GstFormat format;
gint64 start, stop;
format = demux->segment.format;
start =
gst_segment_to_stream_time (&demux->segment, format,
demux->segment.start);
if ((stop = demux->segment.stop) == -1)
stop = demux->segment.duration;
else
stop = gst_segment_to_stream_time (&demux->segment, format, stop);
gst_query_set_segment (query, demux->segment.rate, format, start, stop);
res = TRUE;
break;
}
default:
res = gst_pad_query_default (pad, parent, query);
break;
}
return res;
}
static GstStateChangeReturn
gst_asf_demux_change_state (GstElement * element, GstStateChange transition)
{
GstASFDemux *demux = GST_ASF_DEMUX (element);
GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
switch (transition) {
case GST_STATE_CHANGE_NULL_TO_READY:{
gst_segment_init (&demux->segment, GST_FORMAT_TIME);
demux->need_newsegment = TRUE;
demux->segment_running = FALSE;
demux->keyunit_sync = FALSE;
demux->accurate = FALSE;
demux->adapter = gst_adapter_new ();
demux->metadata = gst_caps_new_empty ();
demux->global_metadata = gst_structure_new_empty ("metadata");
demux->data_size = 0;
demux->data_offset = 0;
demux->index_offset = 0;
demux->base_offset = 0;
demux->flowcombiner = gst_flow_combiner_new ();
break;
}
default:
break;
}
ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
if (ret == GST_STATE_CHANGE_FAILURE)
return ret;
switch (transition) {
case GST_STATE_CHANGE_PAUSED_TO_READY:
gst_asf_demux_reset (demux, FALSE);
break;
case GST_STATE_CHANGE_READY_TO_NULL:
gst_asf_demux_reset (demux, FALSE);
gst_flow_combiner_free (demux->flowcombiner);
demux->flowcombiner = NULL;
break;
default:
break;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3142_0 |
crossvul-cpp_data_bad_3911_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Bitmap Cache V2
*
* Copyright 2011 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 <stdio.h>
#include <winpr/crt.h>
#include <freerdp/freerdp.h>
#include <freerdp/constants.h>
#include <winpr/stream.h>
#include <freerdp/log.h>
#include <freerdp/cache/bitmap.h>
#include <freerdp/gdi/bitmap.h>
#include "../gdi/gdi.h"
#include "../core/graphics.h"
#include "bitmap.h"
#define TAG FREERDP_TAG("cache.bitmap")
static rdpBitmap* bitmap_cache_get(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index);
static BOOL bitmap_cache_put(rdpBitmapCache* bitmap_cache, UINT32 id, UINT32 index,
rdpBitmap* bitmap);
static BOOL update_gdi_memblt(rdpContext* context, MEMBLT_ORDER* memblt)
{
rdpBitmap* bitmap;
rdpCache* cache = context->cache;
if (memblt->cacheId == 0xFF)
bitmap = offscreen_cache_get(cache->offscreen, memblt->cacheIndex);
else
bitmap = bitmap_cache_get(cache->bitmap, (BYTE)memblt->cacheId, memblt->cacheIndex);
/* XP-SP2 servers sometimes ask for cached bitmaps they've never defined. */
if (bitmap == NULL)
return TRUE;
memblt->bitmap = bitmap;
return IFCALLRESULT(TRUE, cache->bitmap->MemBlt, context, memblt);
}
static BOOL update_gdi_mem3blt(rdpContext* context, MEM3BLT_ORDER* mem3blt)
{
BYTE style;
rdpBitmap* bitmap;
rdpCache* cache = context->cache;
rdpBrush* brush = &mem3blt->brush;
BOOL ret = TRUE;
if (mem3blt->cacheId == 0xFF)
bitmap = offscreen_cache_get(cache->offscreen, mem3blt->cacheIndex);
else
bitmap = bitmap_cache_get(cache->bitmap, (BYTE)mem3blt->cacheId, mem3blt->cacheIndex);
/* XP-SP2 servers sometimes ask for cached bitmaps they've never defined. */
if (!bitmap)
return TRUE;
style = brush->style;
if (brush->style & CACHED_BRUSH)
{
brush->data = brush_cache_get(cache->brush, brush->index, &brush->bpp);
if (!brush->data)
return FALSE;
brush->style = 0x03;
}
mem3blt->bitmap = bitmap;
IFCALLRET(cache->bitmap->Mem3Blt, ret, context, mem3blt);
brush->style = style;
return ret;
}
static BOOL update_gdi_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cacheBitmap)
{
rdpBitmap* bitmap;
rdpBitmap* prevBitmap;
rdpCache* cache = context->cache;
bitmap = Bitmap_Alloc(context);
if (!bitmap)
return FALSE;
Bitmap_SetDimensions(bitmap, cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight);
if (!bitmap->Decompress(context, bitmap, cacheBitmap->bitmapDataStream,
cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight,
cacheBitmap->bitmapBpp, cacheBitmap->bitmapLength,
cacheBitmap->compressed, RDP_CODEC_ID_NONE))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
if (!bitmap->New(context, bitmap))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex);
Bitmap_Free(context, prevBitmap);
return bitmap_cache_put(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex, bitmap);
}
static BOOL update_gdi_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cacheBitmapV2)
{
rdpBitmap* bitmap;
rdpBitmap* prevBitmap;
rdpCache* cache = context->cache;
rdpSettings* settings = context->settings;
bitmap = Bitmap_Alloc(context);
if (!bitmap)
return FALSE;
if (!cacheBitmapV2->bitmapBpp)
cacheBitmapV2->bitmapBpp = settings->ColorDepth;
if ((settings->ColorDepth == 15) && (cacheBitmapV2->bitmapBpp == 16))
cacheBitmapV2->bitmapBpp = settings->ColorDepth;
Bitmap_SetDimensions(bitmap, cacheBitmapV2->bitmapWidth, cacheBitmapV2->bitmapHeight);
if (!bitmap->Decompress(context, bitmap, cacheBitmapV2->bitmapDataStream,
cacheBitmapV2->bitmapWidth, cacheBitmapV2->bitmapHeight,
cacheBitmapV2->bitmapBpp, cacheBitmapV2->bitmapLength,
cacheBitmapV2->compressed, RDP_CODEC_ID_NONE))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmapV2->cacheId, cacheBitmapV2->cacheIndex);
if (!bitmap->New(context, bitmap))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
Bitmap_Free(context, prevBitmap);
return bitmap_cache_put(cache->bitmap, cacheBitmapV2->cacheId, cacheBitmapV2->cacheIndex,
bitmap);
}
static BOOL update_gdi_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cacheBitmapV3)
{
rdpBitmap* bitmap;
rdpBitmap* prevBitmap;
BOOL compressed = TRUE;
rdpCache* cache = context->cache;
rdpSettings* settings = context->settings;
BITMAP_DATA_EX* bitmapData = &cacheBitmapV3->bitmapData;
bitmap = Bitmap_Alloc(context);
if (!bitmap)
return FALSE;
if (!cacheBitmapV3->bpp)
cacheBitmapV3->bpp = settings->ColorDepth;
compressed = (bitmapData->codecID != RDP_CODEC_ID_NONE);
Bitmap_SetDimensions(bitmap, bitmapData->width, bitmapData->height);
if (!bitmap->Decompress(context, bitmap, bitmapData->data, bitmapData->width,
bitmapData->height, bitmapData->bpp, bitmapData->length, compressed,
bitmapData->codecID))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
if (!bitmap->New(context, bitmap))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmapV3->cacheId, cacheBitmapV3->cacheIndex);
Bitmap_Free(context, prevBitmap);
return bitmap_cache_put(cache->bitmap, cacheBitmapV3->cacheId, cacheBitmapV3->cacheIndex,
bitmap);
}
rdpBitmap* bitmap_cache_get(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index)
{
rdpBitmap* bitmap;
if (id > bitmapCache->maxCells)
{
WLog_ERR(TAG, "get invalid bitmap cell id: %" PRIu32 "", id);
return NULL;
}
if (index == BITMAP_CACHE_WAITING_LIST_INDEX)
{
index = bitmapCache->cells[id].number;
}
else if (index > bitmapCache->cells[id].number)
{
WLog_ERR(TAG, "get invalid bitmap index %" PRIu32 " in cell id: %" PRIu32 "", index, id);
return NULL;
}
bitmap = bitmapCache->cells[id].entries[index];
return bitmap;
}
BOOL bitmap_cache_put(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index, rdpBitmap* bitmap)
{
if (id > bitmapCache->maxCells)
{
WLog_ERR(TAG, "put invalid bitmap cell id: %" PRIu32 "", id);
return FALSE;
}
if (index == BITMAP_CACHE_WAITING_LIST_INDEX)
{
index = bitmapCache->cells[id].number;
}
else if (index > bitmapCache->cells[id].number)
{
WLog_ERR(TAG, "put invalid bitmap index %" PRIu32 " in cell id: %" PRIu32 "", index, id);
return FALSE;
}
bitmapCache->cells[id].entries[index] = bitmap;
return TRUE;
}
void bitmap_cache_register_callbacks(rdpUpdate* update)
{
rdpCache* cache = update->context->cache;
cache->bitmap->MemBlt = update->primary->MemBlt;
cache->bitmap->Mem3Blt = update->primary->Mem3Blt;
update->primary->MemBlt = update_gdi_memblt;
update->primary->Mem3Blt = update_gdi_mem3blt;
update->secondary->CacheBitmap = update_gdi_cache_bitmap;
update->secondary->CacheBitmapV2 = update_gdi_cache_bitmap_v2;
update->secondary->CacheBitmapV3 = update_gdi_cache_bitmap_v3;
update->BitmapUpdate = gdi_bitmap_update;
}
rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)
{
int i;
rdpBitmapCache* bitmapCache;
bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));
if (!bitmapCache)
return NULL;
bitmapCache->settings = settings;
bitmapCache->update = ((freerdp*)settings->instance)->update;
bitmapCache->context = bitmapCache->update->context;
bitmapCache->maxCells = settings->BitmapCacheV2NumCells;
bitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));
if (!bitmapCache->cells)
goto fail;
for (i = 0; i < (int)bitmapCache->maxCells; i++)
{
bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;
/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */
bitmapCache->cells[i].entries =
(rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));
if (!bitmapCache->cells[i].entries)
goto fail;
}
return bitmapCache;
fail:
if (bitmapCache->cells)
{
for (i = 0; i < (int)bitmapCache->maxCells; i++)
free(bitmapCache->cells[i].entries);
}
free(bitmapCache);
return NULL;
}
void bitmap_cache_free(rdpBitmapCache* bitmapCache)
{
int i, j;
rdpBitmap* bitmap;
if (bitmapCache)
{
for (i = 0; i < (int)bitmapCache->maxCells; i++)
{
for (j = 0; j < (int)bitmapCache->cells[i].number + 1; j++)
{
bitmap = bitmapCache->cells[i].entries[j];
Bitmap_Free(bitmapCache->context, bitmap);
}
free(bitmapCache->cells[i].entries);
}
free(bitmapCache->cells);
free(bitmapCache);
}
}
static void free_bitmap_data(BITMAP_DATA* data, size_t count)
{
size_t x;
if (!data)
return;
for (x = 0; x < count; x++)
free(data[x].bitmapDataStream);
free(data);
}
static BITMAP_DATA* copy_bitmap_data(const BITMAP_DATA* data, size_t count)
{
size_t x;
BITMAP_DATA* dst = (BITMAP_DATA*)calloc(count, sizeof(BITMAP_DATA));
if (!dst)
goto fail;
for (x = 0; x < count; x++)
{
dst[x] = data[x];
if (data[x].bitmapLength > 0)
{
dst[x].bitmapDataStream = malloc(data[x].bitmapLength);
if (!dst[x].bitmapDataStream)
goto fail;
memcpy(dst[x].bitmapDataStream, data[x].bitmapDataStream, data[x].bitmapLength);
}
}
return dst;
fail:
free_bitmap_data(dst, count);
return NULL;
}
void free_bitmap_update(rdpContext* context, BITMAP_UPDATE* pointer)
{
if (!pointer)
return;
free_bitmap_data(pointer->rectangles, pointer->number);
free(pointer);
}
BITMAP_UPDATE* copy_bitmap_update(rdpContext* context, const BITMAP_UPDATE* pointer)
{
BITMAP_UPDATE* dst = calloc(1, sizeof(BITMAP_UPDATE));
if (!dst || !pointer)
goto fail;
*dst = *pointer;
dst->rectangles = copy_bitmap_data(pointer->rectangles, pointer->number);
if (!dst->rectangles)
goto fail;
return dst;
fail:
free_bitmap_update(context, dst);
return NULL;
}
CACHE_BITMAP_ORDER* copy_cache_bitmap_order(rdpContext* context, const CACHE_BITMAP_ORDER* order)
{
CACHE_BITMAP_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_ORDER));
if (!dst || !order)
goto fail;
*dst = *order;
if (order->bitmapLength > 0)
{
dst->bitmapDataStream = malloc(order->bitmapLength);
if (!dst->bitmapDataStream)
goto fail;
memcpy(dst->bitmapDataStream, order->bitmapDataStream, order->bitmapLength);
}
return dst;
fail:
free_cache_bitmap_order(context, dst);
return NULL;
}
void free_cache_bitmap_order(rdpContext* context, CACHE_BITMAP_ORDER* order)
{
if (order)
free(order->bitmapDataStream);
free(order);
}
CACHE_BITMAP_V2_ORDER* copy_cache_bitmap_v2_order(rdpContext* context,
const CACHE_BITMAP_V2_ORDER* order)
{
CACHE_BITMAP_V2_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));
if (!dst || !order)
goto fail;
*dst = *order;
if (order->bitmapLength > 0)
{
dst->bitmapDataStream = malloc(order->bitmapLength);
if (!dst->bitmapDataStream)
goto fail;
memcpy(dst->bitmapDataStream, order->bitmapDataStream, order->bitmapLength);
}
return dst;
fail:
free_cache_bitmap_v2_order(context, dst);
return NULL;
}
void free_cache_bitmap_v2_order(rdpContext* context, CACHE_BITMAP_V2_ORDER* order)
{
if (order)
free(order->bitmapDataStream);
free(order);
}
CACHE_BITMAP_V3_ORDER* copy_cache_bitmap_v3_order(rdpContext* context,
const CACHE_BITMAP_V3_ORDER* order)
{
CACHE_BITMAP_V3_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!dst || !order)
goto fail;
*dst = *order;
if (order->bitmapData.length > 0)
{
dst->bitmapData.data = malloc(order->bitmapData.length);
if (!dst->bitmapData.data)
goto fail;
memcpy(dst->bitmapData.data, order->bitmapData.data, order->bitmapData.length);
}
return dst;
fail:
free_cache_bitmap_v3_order(context, dst);
return NULL;
}
void free_cache_bitmap_v3_order(rdpContext* context, CACHE_BITMAP_V3_ORDER* order)
{
if (order)
free(order->bitmapData.data);
free(order);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3911_0 |
crossvul-cpp_data_good_4689_0 | // SPDX-License-Identifier: GPL-2.0-only
/*
* linux/drivers/block/floppy.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 1993, 1994 Alain Knaff
* Copyright (C) 1998 Alan Cox
*/
/*
* 02.12.91 - Changed to static variables to indicate need for reset
* and recalibrate. This makes some things easier (output_byte reset
* checking etc), and means less interrupt jumping in case of errors,
* so the code is hopefully easier to understand.
*/
/*
* This file is certainly a mess. I've tried my best to get it working,
* but I don't like programming floppies, and I have only one anyway.
* Urgel. I should check for more errors, and do more graceful error
* recovery. Seems there are problems with several drives. I've tried to
* correct them. No promises.
*/
/*
* As with hd.c, all routines within this file can (and will) be called
* by interrupts, so extreme caution is needed. A hardware interrupt
* handler may not sleep, or a kernel panic will happen. Thus I cannot
* call "floppy-on" directly, but have to set a special timer interrupt
* etc.
*/
/*
* 28.02.92 - made track-buffering routines, based on the routines written
* by entropy@wintermute.wpi.edu (Lawrence Foard). Linus.
*/
/*
* Automatic floppy-detection and formatting written by Werner Almesberger
* (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with
* the floppy-change signal detection.
*/
/*
* 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed
* FDC data overrun bug, added some preliminary stuff for vertical
* recording support.
*
* 1992/9/17: Added DMA allocation & DMA functions. -- hhb.
*
* TODO: Errors are still not counted properly.
*/
/* 1992/9/20
* Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl)
* modeled after the freeware MS-DOS program fdformat/88 V1.8 by
* Christoph H. Hochst\"atter.
* I have fixed the shift values to the ones I always use. Maybe a new
* ioctl() should be created to be able to modify them.
* There is a bug in the driver that makes it impossible to format a
* floppy as the first thing after bootup.
*/
/*
* 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and
* this helped the floppy driver as well. Much cleaner, and still seems to
* work.
*/
/* 1994/6/24 --bbroad-- added the floppy table entries and made
* minor modifications to allow 2.88 floppies to be run.
*/
/* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more
* disk types.
*/
/*
* 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger
* format bug fixes, but unfortunately some new bugs too...
*/
/* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write
* errors to allow safe writing by specialized programs.
*/
/* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks
* by defining bit 1 of the "stretch" parameter to mean put sectors on the
* opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's
* drives are "upside-down").
*/
/*
* 1995/8/26 -- Andreas Busse -- added Mips support.
*/
/*
* 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent
* features to asm/floppy.h.
*/
/*
* 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support
*/
/*
* 1998/05/07 -- Russell King -- More portability cleanups; moved definition of
* interrupt and dma channel to asm/floppy.h. Cleaned up some formatting &
* use of '0' for NULL.
*/
/*
* 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation
* failures.
*/
/*
* 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives.
*/
/*
* 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24
* days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were
* being used to store jiffies, which are unsigned longs).
*/
/*
* 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* - get rid of check_region
* - s/suser/capable/
*/
/*
* 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no
* floppy controller (lingering task on list after module is gone... boom.)
*/
/*
* 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range
* (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix
* requires many non-obvious changes in arch dependent code.
*/
/* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>.
* Better audit of register_blkdev.
*/
#undef FLOPPY_SILENT_DCL_CLEAR
#define REALLY_SLOW_IO
#define DEBUGT 2
#define DPRINT(format, args...) \
pr_info("floppy%d: " format, current_drive, ##args)
#define DCL_DEBUG /* debug disk change line */
#ifdef DCL_DEBUG
#define debug_dcl(test, fmt, args...) \
do { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0)
#else
#define debug_dcl(test, fmt, args...) \
do { if (0) DPRINT(fmt, ##args); } while (0)
#endif
/* do print messages for unexpected interrupts */
static int print_unex = 1;
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#define FDPATCHES
#include <linux/fdreg.h>
#include <linux/fd.h>
#include <linux/hdreg.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/bio.h>
#include <linux/string.h>
#include <linux/jiffies.h>
#include <linux/fcntl.h>
#include <linux/delay.h>
#include <linux/mc146818rtc.h> /* CMOS defines */
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#include <linux/mutex.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/async.h>
#include <linux/compat.h>
/*
* PS/2 floppies have much slower step rates than regular floppies.
* It's been recommended that take about 1/4 of the default speed
* in some more extreme cases.
*/
static DEFINE_MUTEX(floppy_mutex);
static int slow_floppy;
#include <asm/dma.h>
#include <asm/irq.h>
static int FLOPPY_IRQ = 6;
static int FLOPPY_DMA = 2;
static int can_use_virtual_dma = 2;
/* =======
* can use virtual DMA:
* 0 = use of virtual DMA disallowed by config
* 1 = use of virtual DMA prescribed by config
* 2 = no virtual DMA preference configured. By default try hard DMA,
* but fall back on virtual DMA when not enough memory available
*/
static int use_virtual_dma;
/* =======
* use virtual DMA
* 0 using hard DMA
* 1 using virtual DMA
* This variable is set to virtual when a DMA mem problem arises, and
* reset back in floppy_grab_irq_and_dma.
* It is not safe to reset it in other circumstances, because the floppy
* driver may have several buffers in use at once, and we do currently not
* record each buffers capabilities
*/
static DEFINE_SPINLOCK(floppy_lock);
static unsigned short virtual_dma_port = 0x3f0;
irqreturn_t floppy_interrupt(int irq, void *dev_id);
static int set_dor(int fdc, char mask, char data);
#define K_64 0x10000 /* 64KB */
/* the following is the mask of allowed drives. By default units 2 and
* 3 of both floppy controllers are disabled, because switching on the
* motor of these drives causes system hangs on some PCI computers. drive
* 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if
* a drive is allowed.
*
* NOTE: This must come before we include the arch floppy header because
* some ports reference this variable from there. -DaveM
*/
static int allowed_drive_mask = 0x33;
#include <asm/floppy.h>
static int irqdma_allocated;
#include <linux/blk-mq.h>
#include <linux/blkpg.h>
#include <linux/cdrom.h> /* for the compatibility eject ioctl */
#include <linux/completion.h>
static LIST_HEAD(floppy_reqs);
static struct request *current_req;
static int set_next_request(void);
#ifndef fd_get_dma_residue
#define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)
#endif
/* Dma Memory related stuff */
#ifndef fd_dma_mem_free
#define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))
#endif
#ifndef fd_dma_mem_alloc
#define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size))
#endif
#ifndef fd_cacheflush
#define fd_cacheflush(addr, size) /* nothing... */
#endif
static inline void fallback_on_nodma_alloc(char **addr, size_t l)
{
#ifdef FLOPPY_CAN_FALLBACK_ON_NODMA
if (*addr)
return; /* we have the memory */
if (can_use_virtual_dma != 2)
return; /* no fallback allowed */
pr_info("DMA memory shortage. Temporarily falling back on virtual DMA\n");
*addr = (char *)nodma_mem_alloc(l);
#else
return;
#endif
}
/* End dma memory related stuff */
static unsigned long fake_change;
static bool initialized;
#define ITYPE(x) (((x) >> 2) & 0x1f)
#define TOMINOR(x) ((x & 3) | ((x & 4) << 5))
#define UNIT(x) ((x) & 0x03) /* drive on fdc */
#define FDC(x) (((x) & 0x04) >> 2) /* fdc of drive */
/* reverse mapping from unit and fdc to drive */
#define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))
#define DP (&drive_params[current_drive])
#define DRS (&drive_state[current_drive])
#define DRWE (&write_errors[current_drive])
#define FDCS (&fdc_state[fdc])
#define UDP (&drive_params[drive])
#define UDRS (&drive_state[drive])
#define UDRWE (&write_errors[drive])
#define UFDCS (&fdc_state[FDC(drive)])
#define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2)
#define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH)
/* read/write */
#define COMMAND (raw_cmd->cmd[0])
#define DR_SELECT (raw_cmd->cmd[1])
#define TRACK (raw_cmd->cmd[2])
#define HEAD (raw_cmd->cmd[3])
#define SECTOR (raw_cmd->cmd[4])
#define SIZECODE (raw_cmd->cmd[5])
#define SECT_PER_TRACK (raw_cmd->cmd[6])
#define GAP (raw_cmd->cmd[7])
#define SIZECODE2 (raw_cmd->cmd[8])
#define NR_RW 9
/* format */
#define F_SIZECODE (raw_cmd->cmd[2])
#define F_SECT_PER_TRACK (raw_cmd->cmd[3])
#define F_GAP (raw_cmd->cmd[4])
#define F_FILL (raw_cmd->cmd[5])
#define NR_F 6
/*
* Maximum disk size (in kilobytes).
* This default is used whenever the current disk size is unknown.
* [Now it is rather a minimum]
*/
#define MAX_DISK_SIZE 4 /* 3984 */
/*
* globals used by 'result()'
*/
#define MAX_REPLIES 16
static unsigned char reply_buffer[MAX_REPLIES];
static int inr; /* size of reply buffer, when called from interrupt */
#define ST0 (reply_buffer[0])
#define ST1 (reply_buffer[1])
#define ST2 (reply_buffer[2])
#define ST3 (reply_buffer[0]) /* result of GETSTATUS */
#define R_TRACK (reply_buffer[3])
#define R_HEAD (reply_buffer[4])
#define R_SECTOR (reply_buffer[5])
#define R_SIZECODE (reply_buffer[6])
#define SEL_DLY (2 * HZ / 100)
/*
* this struct defines the different floppy drive types.
*/
static struct {
struct floppy_drive_params params;
const char *name; /* name printed while booting */
} default_drive_params[] = {
/* NOTE: the time values in jiffies should be in msec!
CMOS drive type
| Maximum data rate supported by drive type
| | Head load time, msec
| | | Head unload time, msec (not used)
| | | | Step rate interval, usec
| | | | | Time needed for spinup time (jiffies)
| | | | | | Timeout for spinning down (jiffies)
| | | | | | | Spindown offset (where disk stops)
| | | | | | | | Select delay
| | | | | | | | | RPS
| | | | | | | | | | Max number of tracks
| | | | | | | | | | | Interrupt timeout
| | | | | | | | | | | | Max nonintlv. sectors
| | | | | | | | | | | | | -Max Errors- flags */
{{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0,
0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" },
{{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0,
0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/
{{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0,
0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/
{{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,
0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/
{{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,
0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/
{{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,
0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/
{{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,
0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/
/* | --autodetected formats--- | | |
* read_track | | Name printed when booting
* | Native format
* Frequency of disk change checks */
};
static struct floppy_drive_params drive_params[N_DRIVE];
static struct floppy_drive_struct drive_state[N_DRIVE];
static struct floppy_write_errors write_errors[N_DRIVE];
static struct timer_list motor_off_timer[N_DRIVE];
static struct gendisk *disks[N_DRIVE];
static struct blk_mq_tag_set tag_sets[N_DRIVE];
static struct block_device *opened_bdev[N_DRIVE];
static DEFINE_MUTEX(open_lock);
static struct floppy_raw_cmd *raw_cmd, default_raw_cmd;
/*
* This struct defines the different floppy types.
*
* Bit 0 of 'stretch' tells if the tracks need to be doubled for some
* types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch'
* tells if the disk is in Commodore 1581 format, which means side 0 sectors
* are located on side 1 of the disk but with a side 0 ID, and vice-versa.
* This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the
* 1581's logical side 0 is on physical side 1, whereas the Sharp's logical
* side 0 is on physical side 0 (but with the misnamed sector IDs).
* 'stretch' should probably be renamed to something more general, like
* 'options'.
*
* Bits 2 through 9 of 'stretch' tell the number of the first sector.
* The LSB (bit 2) is flipped. For most disks, the first sector
* is 1 (represented by 0x00<<2). For some CP/M and music sampler
* disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2).
* For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2).
*
* Other parameters should be self-explanatory (see also setfdprm(8)).
*/
/*
Size
| Sectors per track
| | Head
| | | Tracks
| | | | Stretch
| | | | | Gap 1 size
| | | | | | Data rate, | 0x40 for perp
| | | | | | | Spec1 (stepping rate, head unload
| | | | | | | | /fmt gap (gap2) */
static struct floppy_struct floppy_type[32] = {
{ 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL }, /* 0 no testing */
{ 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360" }, /* 1 360KB PC */
{ 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /* 2 1.2MB AT */
{ 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360" }, /* 3 360KB SS 3.5" */
{ 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720" }, /* 4 720KB 3.5" */
{ 720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360" }, /* 5 360KB AT */
{ 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720" }, /* 6 720KB AT */
{ 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /* 7 1.44MB 3.5" */
{ 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /* 8 2.88MB 3.5" */
{ 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /* 9 3.12MB 3.5" */
{ 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25" */
{ 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5" */
{ 820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410" }, /* 12 410KB 5.25" */
{ 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820" }, /* 13 820KB 3.5" */
{ 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25" */
{ 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5" */
{ 840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420" }, /* 16 420KB 5.25" */
{ 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830" }, /* 17 830KB 3.5" */
{ 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25" */
{ 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5" */
{ 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880" }, /* 20 880KB 5.25" */
{ 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5" */
{ 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5" */
{ 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25" */
{ 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5" */
{ 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5" */
{ 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5" */
{ 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5" */
{ 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5" */
{ 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5" */
{ 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800" }, /* 30 800KB 3.5" */
{ 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5" */
};
#define SECTSIZE (_FD_SECTSIZE(*floppy))
/* Auto-detection: Disk type used until the next media change occurs. */
static struct floppy_struct *current_type[N_DRIVE];
/*
* User-provided type information. current_type points to
* the respective entry of this array.
*/
static struct floppy_struct user_params[N_DRIVE];
static sector_t floppy_sizes[256];
static char floppy_device_name[] = "floppy";
/*
* The driver is trying to determine the correct media format
* while probing is set. rw_interrupt() clears it after a
* successful access.
*/
static int probing;
/* Synchronization of FDC access. */
#define FD_COMMAND_NONE -1
#define FD_COMMAND_ERROR 2
#define FD_COMMAND_OKAY 3
static volatile int command_status = FD_COMMAND_NONE;
static unsigned long fdc_busy;
static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
static DECLARE_WAIT_QUEUE_HEAD(command_done);
/* Errors during formatting are counted here. */
static int format_errors;
/* Format request descriptor. */
static struct format_descr format_req;
/*
* Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps
* Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),
* H is head unload time (1=16ms, 2=32ms, etc)
*/
/*
* Track buffer
* Because these are written to by the DMA controller, they must
* not contain a 64k byte boundary crossing, or data will be
* corrupted/lost.
*/
static char *floppy_track_buffer;
static int max_buffer_sectors;
static int *errors;
typedef void (*done_f)(int);
static const struct cont_t {
void (*interrupt)(void);
/* this is called after the interrupt of the
* main command */
void (*redo)(void); /* this is called to retry the operation */
void (*error)(void); /* this is called to tally an error */
done_f done; /* this is called to say if the operation has
* succeeded/failed */
} *cont;
static void floppy_ready(void);
static void floppy_start(void);
static void process_fd_request(void);
static void recalibrate_floppy(void);
static void floppy_shutdown(struct work_struct *);
static int floppy_request_regions(int);
static void floppy_release_regions(int);
static int floppy_grab_irq_and_dma(void);
static void floppy_release_irq_and_dma(void);
/*
* The "reset" variable should be tested whenever an interrupt is scheduled,
* after the commands have been sent. This is to ensure that the driver doesn't
* get wedged when the interrupt doesn't come because of a failed command.
* reset doesn't need to be tested before sending commands, because
* output_byte is automatically disabled when reset is set.
*/
static void reset_fdc(void);
/*
* These are global variables, as that's the easiest way to give
* information to interrupts. They are the data used for the current
* request.
*/
#define NO_TRACK -1
#define NEED_1_RECAL -2
#define NEED_2_RECAL -3
static atomic_t usage_count = ATOMIC_INIT(0);
/* buffer related variables */
static int buffer_track = -1;
static int buffer_drive = -1;
static int buffer_min = -1;
static int buffer_max = -1;
/* fdc related variables, should end up in a struct */
static struct floppy_fdc_state fdc_state[N_FDC];
static int fdc; /* current fdc */
static struct workqueue_struct *floppy_wq;
static struct floppy_struct *_floppy = floppy_type;
static unsigned char current_drive;
static long current_count_sectors;
static unsigned char fsector_t; /* sector in track */
static unsigned char in_sector_offset; /* offset within physical sector,
* expressed in units of 512 bytes */
static inline bool drive_no_geom(int drive)
{
return !current_type[drive] && !ITYPE(UDRS->fd_device);
}
#ifndef fd_eject
static inline int fd_eject(int drive)
{
return -EINVAL;
}
#endif
/*
* Debugging
* =========
*/
#ifdef DEBUGT
static long unsigned debugtimer;
static inline void set_debugt(void)
{
debugtimer = jiffies;
}
static inline void debugt(const char *func, const char *msg)
{
if (DP->flags & DEBUGT)
pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer);
}
#else
static inline void set_debugt(void) { }
static inline void debugt(const char *func, const char *msg) { }
#endif /* DEBUGT */
static DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown);
static const char *timeout_message;
static void is_alive(const char *func, const char *message)
{
/* this routine checks whether the floppy driver is "alive" */
if (test_bit(0, &fdc_busy) && command_status < 2 &&
!delayed_work_pending(&fd_timeout)) {
DPRINT("%s: timeout handler died. %s\n", func, message);
}
}
static void (*do_floppy)(void) = NULL;
#define OLOGSIZE 20
static void (*lasthandler)(void);
static unsigned long interruptjiffies;
static unsigned long resultjiffies;
static int resultsize;
static unsigned long lastredo;
static struct output_log {
unsigned char data;
unsigned char status;
unsigned long jiffies;
} output_log[OLOGSIZE];
static int output_log_pos;
#define current_reqD -1
#define MAXTIMEOUT -2
static void __reschedule_timeout(int drive, const char *message)
{
unsigned long delay;
if (drive == current_reqD)
drive = current_drive;
if (drive < 0 || drive >= N_DRIVE) {
delay = 20UL * HZ;
drive = 0;
} else
delay = UDP->timeout;
mod_delayed_work(floppy_wq, &fd_timeout, delay);
if (UDP->flags & FD_DEBUG)
DPRINT("reschedule timeout %s\n", message);
timeout_message = message;
}
static void reschedule_timeout(int drive, const char *message)
{
unsigned long flags;
spin_lock_irqsave(&floppy_lock, flags);
__reschedule_timeout(drive, message);
spin_unlock_irqrestore(&floppy_lock, flags);
}
#define INFBOUND(a, b) (a) = max_t(int, a, b)
#define SUPBOUND(a, b) (a) = min_t(int, a, b)
/*
* Bottom half floppy driver.
* ==========================
*
* This part of the file contains the code talking directly to the hardware,
* and also the main service loop (seek-configure-spinup-command)
*/
/*
* disk change.
* This routine is responsible for maintaining the FD_DISK_CHANGE flag,
* and the last_checked date.
*
* last_checked is the date of the last check which showed 'no disk change'
* FD_DISK_CHANGE is set under two conditions:
* 1. The floppy has been changed after some i/o to that floppy already
* took place.
* 2. No floppy disk is in the drive. This is done in order to ensure that
* requests are quickly flushed in case there is no disk in the drive. It
* follows that FD_DISK_CHANGE can only be cleared if there is a disk in
* the drive.
*
* For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.
* For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on
* each seek. If a disk is present, the disk change line should also be
* cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk
* change line is set, this means either that no disk is in the drive, or
* that it has been removed since the last seek.
*
* This means that we really have a third possibility too:
* The floppy has been changed after the last seek.
*/
static int disk_change(int drive)
{
int fdc = FDC(drive);
if (time_before(jiffies, UDRS->select_date + UDP->select_delay))
DPRINT("WARNING disk change called early\n");
if (!(FDCS->dor & (0x10 << UNIT(drive))) ||
(FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) {
DPRINT("probing disk change on unselected drive\n");
DPRINT("drive=%d fdc=%d dor=%x\n", drive, FDC(drive),
(unsigned int)FDCS->dor);
}
debug_dcl(UDP->flags,
"checking disk change line for drive %d\n", drive);
debug_dcl(UDP->flags, "jiffies=%lu\n", jiffies);
debug_dcl(UDP->flags, "disk change line=%x\n", fd_inb(FD_DIR) & 0x80);
debug_dcl(UDP->flags, "flags=%lx\n", UDRS->flags);
if (UDP->flags & FD_BROKEN_DCL)
return test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) {
set_bit(FD_VERIFY_BIT, &UDRS->flags);
/* verify write protection */
if (UDRS->maxblock) /* mark it changed */
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
/* invalidate its geometry */
if (UDRS->keep_data >= 0) {
if ((UDP->flags & FTD_MSG) &&
current_type[drive] != NULL)
DPRINT("Disk type is undefined after disk change\n");
current_type[drive] = NULL;
floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1;
}
return 1;
} else {
UDRS->last_checked = jiffies;
clear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);
}
return 0;
}
static inline int is_selected(int dor, int unit)
{
return ((dor & (0x10 << unit)) && (dor & 3) == unit);
}
static bool is_ready_state(int status)
{
int state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA);
return state == STATUS_READY;
}
static int set_dor(int fdc, char mask, char data)
{
unsigned char unit;
unsigned char drive;
unsigned char newdor;
unsigned char olddor;
if (FDCS->address == -1)
return -1;
olddor = FDCS->dor;
newdor = (olddor & mask) | data;
if (newdor != olddor) {
unit = olddor & 0x3;
if (is_selected(olddor, unit) && !is_selected(newdor, unit)) {
drive = REVDRIVE(fdc, unit);
debug_dcl(UDP->flags,
"calling disk change from set_dor\n");
disk_change(drive);
}
FDCS->dor = newdor;
fd_outb(newdor, FD_DOR);
unit = newdor & 0x3;
if (!is_selected(olddor, unit) && is_selected(newdor, unit)) {
drive = REVDRIVE(fdc, unit);
UDRS->select_date = jiffies;
}
}
return olddor;
}
static void twaddle(void)
{
if (DP->select_delay)
return;
fd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR);
fd_outb(FDCS->dor, FD_DOR);
DRS->select_date = jiffies;
}
/*
* Reset all driver information about the current fdc.
* This is needed after a reset, and after a raw command.
*/
static void reset_fdc_info(int mode)
{
int drive;
FDCS->spec1 = FDCS->spec2 = -1;
FDCS->need_configure = 1;
FDCS->perp_mode = 1;
FDCS->rawcmd = 0;
for (drive = 0; drive < N_DRIVE; drive++)
if (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL))
UDRS->track = NEED_2_RECAL;
}
/* selects the fdc and drive, and enables the fdc's input/dma. */
static void set_fdc(int drive)
{
unsigned int new_fdc = fdc;
if (drive >= 0 && drive < N_DRIVE) {
new_fdc = FDC(drive);
current_drive = drive;
}
if (new_fdc >= N_FDC) {
pr_info("bad fdc value\n");
return;
}
fdc = new_fdc;
set_dor(fdc, ~0, 8);
#if N_FDC > 1
set_dor(1 - fdc, ~8, 0);
#endif
if (FDCS->rawcmd == 2)
reset_fdc_info(1);
if (fd_inb(FD_STATUS) != STATUS_READY)
FDCS->reset = 1;
}
/* locks the driver */
static int lock_fdc(int drive)
{
if (WARN(atomic_read(&usage_count) == 0,
"Trying to lock fdc while usage count=0\n"))
return -1;
if (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy)))
return -EINTR;
command_status = FD_COMMAND_NONE;
reschedule_timeout(drive, "lock fdc");
set_fdc(drive);
return 0;
}
/* unlocks the driver */
static void unlock_fdc(void)
{
if (!test_bit(0, &fdc_busy))
DPRINT("FDC access conflict!\n");
raw_cmd = NULL;
command_status = FD_COMMAND_NONE;
cancel_delayed_work(&fd_timeout);
do_floppy = NULL;
cont = NULL;
clear_bit(0, &fdc_busy);
wake_up(&fdc_wait);
}
/* switches the motor off after a given timeout */
static void motor_off_callback(struct timer_list *t)
{
unsigned long nr = t - motor_off_timer;
unsigned char mask = ~(0x10 << UNIT(nr));
if (WARN_ON_ONCE(nr >= N_DRIVE))
return;
set_dor(FDC(nr), mask, 0);
}
/* schedules motor off */
static void floppy_off(unsigned int drive)
{
unsigned long volatile delta;
int fdc = FDC(drive);
if (!(FDCS->dor & (0x10 << UNIT(drive))))
return;
del_timer(motor_off_timer + drive);
/* make spindle stop in a position which minimizes spinup time
* next time */
if (UDP->rps) {
delta = jiffies - UDRS->first_read_date + HZ -
UDP->spindown_offset;
delta = ((delta * UDP->rps) % HZ) / UDP->rps;
motor_off_timer[drive].expires =
jiffies + UDP->spindown - delta;
}
add_timer(motor_off_timer + drive);
}
/*
* cycle through all N_DRIVE floppy drives, for disk change testing.
* stopping at current drive. This is done before any long operation, to
* be sure to have up to date disk change information.
*/
static void scandrives(void)
{
int i;
int drive;
int saved_drive;
if (DP->select_delay)
return;
saved_drive = current_drive;
for (i = 0; i < N_DRIVE; i++) {
drive = (saved_drive + i + 1) % N_DRIVE;
if (UDRS->fd_ref == 0 || UDP->select_delay != 0)
continue; /* skip closed drives */
set_fdc(drive);
if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) &
(0x10 << UNIT(drive))))
/* switch the motor off again, if it was off to
* begin with */
set_dor(fdc, ~(0x10 << UNIT(drive)), 0);
}
set_fdc(saved_drive);
}
static void empty(void)
{
}
static void (*floppy_work_fn)(void);
static void floppy_work_workfn(struct work_struct *work)
{
floppy_work_fn();
}
static DECLARE_WORK(floppy_work, floppy_work_workfn);
static void schedule_bh(void (*handler)(void))
{
WARN_ON(work_pending(&floppy_work));
floppy_work_fn = handler;
queue_work(floppy_wq, &floppy_work);
}
static void (*fd_timer_fn)(void) = NULL;
static void fd_timer_workfn(struct work_struct *work)
{
fd_timer_fn();
}
static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn);
static void cancel_activity(void)
{
do_floppy = NULL;
cancel_delayed_work_sync(&fd_timer);
cancel_work_sync(&floppy_work);
}
/* this function makes sure that the disk stays in the drive during the
* transfer */
static void fd_watchdog(void)
{
debug_dcl(DP->flags, "calling disk change from watchdog\n");
if (disk_change(current_drive)) {
DPRINT("disk removed during i/o\n");
cancel_activity();
cont->done(0);
reset_fdc();
} else {
cancel_delayed_work(&fd_timer);
fd_timer_fn = fd_watchdog;
queue_delayed_work(floppy_wq, &fd_timer, HZ / 10);
}
}
static void main_command_interrupt(void)
{
cancel_delayed_work(&fd_timer);
cont->interrupt();
}
/* waits for a delay (spinup or select) to pass */
static int fd_wait_for_completion(unsigned long expires,
void (*function)(void))
{
if (FDCS->reset) {
reset_fdc(); /* do the reset during sleep to win time
* if we don't need to sleep, it's a good
* occasion anyways */
return 1;
}
if (time_before(jiffies, expires)) {
cancel_delayed_work(&fd_timer);
fd_timer_fn = function;
queue_delayed_work(floppy_wq, &fd_timer, expires - jiffies);
return 1;
}
return 0;
}
static void setup_DMA(void)
{
unsigned long f;
if (raw_cmd->length == 0) {
int i;
pr_info("zero dma transfer size:");
for (i = 0; i < raw_cmd->cmd_count; i++)
pr_cont("%x,", raw_cmd->cmd[i]);
pr_cont("\n");
cont->done(0);
FDCS->reset = 1;
return;
}
if (((unsigned long)raw_cmd->kernel_data) % 512) {
pr_info("non aligned address: %p\n", raw_cmd->kernel_data);
cont->done(0);
FDCS->reset = 1;
return;
}
f = claim_dma_lock();
fd_disable_dma();
#ifdef fd_dma_setup
if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length,
(raw_cmd->flags & FD_RAW_READ) ?
DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) {
release_dma_lock(f);
cont->done(0);
FDCS->reset = 1;
return;
}
release_dma_lock(f);
#else
fd_clear_dma_ff();
fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length);
fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ?
DMA_MODE_READ : DMA_MODE_WRITE);
fd_set_dma_addr(raw_cmd->kernel_data);
fd_set_dma_count(raw_cmd->length);
virtual_dma_port = FDCS->address;
fd_enable_dma();
release_dma_lock(f);
#endif
}
static void show_floppy(void);
/* waits until the fdc becomes ready */
static int wait_til_ready(void)
{
int status;
int counter;
if (FDCS->reset)
return -1;
for (counter = 0; counter < 10000; counter++) {
status = fd_inb(FD_STATUS);
if (status & STATUS_READY)
return status;
}
if (initialized) {
DPRINT("Getstatus times out (%x) on fdc %d\n", status, fdc);
show_floppy();
}
FDCS->reset = 1;
return -1;
}
/* sends a command byte to the fdc */
static int output_byte(char byte)
{
int status = wait_til_ready();
if (status < 0)
return -1;
if (is_ready_state(status)) {
fd_outb(byte, FD_DATA);
output_log[output_log_pos].data = byte;
output_log[output_log_pos].status = status;
output_log[output_log_pos].jiffies = jiffies;
output_log_pos = (output_log_pos + 1) % OLOGSIZE;
return 0;
}
FDCS->reset = 1;
if (initialized) {
DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n",
byte, fdc, status);
show_floppy();
}
return -1;
}
/* gets the response from the fdc */
static int result(void)
{
int i;
int status = 0;
for (i = 0; i < MAX_REPLIES; i++) {
status = wait_til_ready();
if (status < 0)
break;
status &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA;
if ((status & ~STATUS_BUSY) == STATUS_READY) {
resultjiffies = jiffies;
resultsize = i;
return i;
}
if (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY))
reply_buffer[i] = fd_inb(FD_DATA);
else
break;
}
if (initialized) {
DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n",
fdc, status, i);
show_floppy();
}
FDCS->reset = 1;
return -1;
}
#define MORE_OUTPUT -2
/* does the fdc need more output? */
static int need_more_output(void)
{
int status = wait_til_ready();
if (status < 0)
return -1;
if (is_ready_state(status))
return MORE_OUTPUT;
return result();
}
/* Set perpendicular mode as required, based on data rate, if supported.
* 82077 Now tested. 1Mbps data rate only possible with 82077-1.
*/
static void perpendicular_mode(void)
{
unsigned char perp_mode;
if (raw_cmd->rate & 0x40) {
switch (raw_cmd->rate & 3) {
case 0:
perp_mode = 2;
break;
case 3:
perp_mode = 3;
break;
default:
DPRINT("Invalid data rate for perpendicular mode!\n");
cont->done(0);
FDCS->reset = 1;
/*
* convenient way to return to
* redo without too much hassle
* (deep stack et al.)
*/
return;
}
} else
perp_mode = 0;
if (FDCS->perp_mode == perp_mode)
return;
if (FDCS->version >= FDC_82077_ORIG) {
output_byte(FD_PERPENDICULAR);
output_byte(perp_mode);
FDCS->perp_mode = perp_mode;
} else if (perp_mode) {
DPRINT("perpendicular mode not supported by this FDC.\n");
}
} /* perpendicular_mode */
static int fifo_depth = 0xa;
static int no_fifo;
static int fdc_configure(void)
{
/* Turn on FIFO */
output_byte(FD_CONFIGURE);
if (need_more_output() != MORE_OUTPUT)
return 0;
output_byte(0);
output_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf));
output_byte(0); /* pre-compensation from track
0 upwards */
return 1;
}
#define NOMINAL_DTR 500
/* Issue a "SPECIFY" command to set the step rate time, head unload time,
* head load time, and DMA disable flag to values needed by floppy.
*
* The value "dtr" is the data transfer rate in Kbps. It is needed
* to account for the data rate-based scaling done by the 82072 and 82077
* FDC types. This parameter is ignored for other types of FDCs (i.e.
* 8272a).
*
* Note that changing the data transfer rate has a (probably deleterious)
* effect on the parameters subject to scaling for 82072/82077 FDCs, so
* fdc_specify is called again after each data transfer rate
* change.
*
* srt: 1000 to 16000 in microseconds
* hut: 16 to 240 milliseconds
* hlt: 2 to 254 milliseconds
*
* These values are rounded up to the next highest available delay time.
*/
static void fdc_specify(void)
{
unsigned char spec1;
unsigned char spec2;
unsigned long srt;
unsigned long hlt;
unsigned long hut;
unsigned long dtr = NOMINAL_DTR;
unsigned long scale_dtr = NOMINAL_DTR;
int hlt_max_code = 0x7f;
int hut_max_code = 0xf;
if (FDCS->need_configure && FDCS->version >= FDC_82072A) {
fdc_configure();
FDCS->need_configure = 0;
}
switch (raw_cmd->rate & 0x03) {
case 3:
dtr = 1000;
break;
case 1:
dtr = 300;
if (FDCS->version >= FDC_82078) {
/* chose the default rate table, not the one
* where 1 = 2 Mbps */
output_byte(FD_DRIVESPEC);
if (need_more_output() == MORE_OUTPUT) {
output_byte(UNIT(current_drive));
output_byte(0xc0);
}
}
break;
case 2:
dtr = 250;
break;
}
if (FDCS->version >= FDC_82072) {
scale_dtr = dtr;
hlt_max_code = 0x00; /* 0==256msec*dtr0/dtr (not linear!) */
hut_max_code = 0x0; /* 0==256msec*dtr0/dtr (not linear!) */
}
/* Convert step rate from microseconds to milliseconds and 4 bits */
srt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR);
if (slow_floppy)
srt = srt / 4;
SUPBOUND(srt, 0xf);
INFBOUND(srt, 0);
hlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR);
if (hlt < 0x01)
hlt = 0x01;
else if (hlt > 0x7f)
hlt = hlt_max_code;
hut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR);
if (hut < 0x1)
hut = 0x1;
else if (hut > 0xf)
hut = hut_max_code;
spec1 = (srt << 4) | hut;
spec2 = (hlt << 1) | (use_virtual_dma & 1);
/* If these parameters did not change, just return with success */
if (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) {
/* Go ahead and set spec1 and spec2 */
output_byte(FD_SPECIFY);
output_byte(FDCS->spec1 = spec1);
output_byte(FDCS->spec2 = spec2);
}
} /* fdc_specify */
/* Set the FDC's data transfer rate on behalf of the specified drive.
* NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue
* of the specify command (i.e. using the fdc_specify function).
*/
static int fdc_dtr(void)
{
/* If data rate not already set to desired value, set it. */
if ((raw_cmd->rate & 3) == FDCS->dtr)
return 0;
/* Set dtr */
fd_outb(raw_cmd->rate & 3, FD_DCR);
/* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB)
* need a stabilization period of several milliseconds to be
* enforced after data rate changes before R/W operations.
* Pause 5 msec to avoid trouble. (Needs to be 2 jiffies)
*/
FDCS->dtr = raw_cmd->rate & 3;
return fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready);
} /* fdc_dtr */
static void tell_sector(void)
{
pr_cont(": track %d, head %d, sector %d, size %d",
R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE);
} /* tell_sector */
static void print_errors(void)
{
DPRINT("");
if (ST0 & ST0_ECE) {
pr_cont("Recalibrate failed!");
} else if (ST2 & ST2_CRC) {
pr_cont("data CRC error");
tell_sector();
} else if (ST1 & ST1_CRC) {
pr_cont("CRC error");
tell_sector();
} else if ((ST1 & (ST1_MAM | ST1_ND)) ||
(ST2 & ST2_MAM)) {
if (!probing) {
pr_cont("sector not found");
tell_sector();
} else
pr_cont("probe failed...");
} else if (ST2 & ST2_WC) { /* seek error */
pr_cont("wrong cylinder");
} else if (ST2 & ST2_BC) { /* cylinder marked as bad */
pr_cont("bad cylinder");
} else {
pr_cont("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x",
ST0, ST1, ST2);
tell_sector();
}
pr_cont("\n");
}
/*
* OK, this error interpreting routine is called after a
* DMA read/write has succeeded
* or failed, so we check the results, and copy any buffers.
* hhb: Added better error reporting.
* ak: Made this into a separate routine.
*/
static int interpret_errors(void)
{
char bad;
if (inr != 7) {
DPRINT("-- FDC reply error\n");
FDCS->reset = 1;
return 1;
}
/* check IC to find cause of interrupt */
switch (ST0 & ST0_INTR) {
case 0x40: /* error occurred during command execution */
if (ST1 & ST1_EOC)
return 0; /* occurs with pseudo-DMA */
bad = 1;
if (ST1 & ST1_WP) {
DPRINT("Drive is write protected\n");
clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);
cont->done(0);
bad = 2;
} else if (ST1 & ST1_ND) {
set_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);
} else if (ST1 & ST1_OR) {
if (DP->flags & FTD_MSG)
DPRINT("Over/Underrun - retrying\n");
bad = 0;
} else if (*errors >= DP->max_errors.reporting) {
print_errors();
}
if (ST2 & ST2_WC || ST2 & ST2_BC)
/* wrong cylinder => recal */
DRS->track = NEED_2_RECAL;
return bad;
case 0x80: /* invalid command given */
DPRINT("Invalid FDC command given!\n");
cont->done(0);
return 2;
case 0xc0:
DPRINT("Abnormal termination caused by polling\n");
cont->error();
return 2;
default: /* (0) Normal command termination */
return 0;
}
}
/*
* This routine is called when everything should be correctly set up
* for the transfer (i.e. floppy motor is on, the correct floppy is
* selected, and the head is sitting on the right track).
*/
static void setup_rw_floppy(void)
{
int i;
int r;
int flags;
unsigned long ready_date;
void (*function)(void);
flags = raw_cmd->flags;
if (flags & (FD_RAW_READ | FD_RAW_WRITE))
flags |= FD_RAW_INTR;
if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) {
ready_date = DRS->spinup_date + DP->spinup;
/* If spinup will take a long time, rerun scandrives
* again just before spinup completion. Beware that
* after scandrives, we must again wait for selection.
*/
if (time_after(ready_date, jiffies + DP->select_delay)) {
ready_date -= DP->select_delay;
function = floppy_start;
} else
function = setup_rw_floppy;
/* wait until the floppy is spinning fast enough */
if (fd_wait_for_completion(ready_date, function))
return;
}
if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE))
setup_DMA();
if (flags & FD_RAW_INTR)
do_floppy = main_command_interrupt;
r = 0;
for (i = 0; i < raw_cmd->cmd_count; i++)
r |= output_byte(raw_cmd->cmd[i]);
debugt(__func__, "rw_command");
if (r) {
cont->error();
reset_fdc();
return;
}
if (!(flags & FD_RAW_INTR)) {
inr = result();
cont->interrupt();
} else if (flags & FD_RAW_NEED_DISK)
fd_watchdog();
}
static int blind_seek;
/*
* This is the routine called after every seek (or recalibrate) interrupt
* from the floppy controller.
*/
static void seek_interrupt(void)
{
debugt(__func__, "");
if (inr != 2 || (ST0 & 0xF8) != 0x20) {
DPRINT("seek failed\n");
DRS->track = NEED_2_RECAL;
cont->error();
cont->redo();
return;
}
if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) {
debug_dcl(DP->flags,
"clearing NEWCHANGE flag because of effective seek\n");
debug_dcl(DP->flags, "jiffies=%lu\n", jiffies);
clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
/* effective seek */
DRS->select_date = jiffies;
}
DRS->track = ST1;
floppy_ready();
}
static void check_wp(void)
{
if (test_bit(FD_VERIFY_BIT, &DRS->flags)) {
/* check write protection */
output_byte(FD_GETSTATUS);
output_byte(UNIT(current_drive));
if (result() != 1) {
FDCS->reset = 1;
return;
}
clear_bit(FD_VERIFY_BIT, &DRS->flags);
clear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);
debug_dcl(DP->flags,
"checking whether disk is write protected\n");
debug_dcl(DP->flags, "wp=%x\n", ST3 & 0x40);
if (!(ST3 & 0x40))
set_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);
else
clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);
}
}
static void seek_floppy(void)
{
int track;
blind_seek = 0;
debug_dcl(DP->flags, "calling disk change from %s\n", __func__);
if (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&
disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) {
/* the media changed flag should be cleared after the seek.
* If it isn't, this means that there is really no disk in
* the drive.
*/
set_bit(FD_DISK_CHANGED_BIT, &DRS->flags);
cont->done(0);
cont->redo();
return;
}
if (DRS->track <= NEED_1_RECAL) {
recalibrate_floppy();
return;
} else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&
(raw_cmd->flags & FD_RAW_NEED_DISK) &&
(DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) {
/* we seek to clear the media-changed condition. Does anybody
* know a more elegant way, which works on all drives? */
if (raw_cmd->track)
track = raw_cmd->track - 1;
else {
if (DP->flags & FD_SILENT_DCL_CLEAR) {
set_dor(fdc, ~(0x10 << UNIT(current_drive)), 0);
blind_seek = 1;
raw_cmd->flags |= FD_RAW_NEED_SEEK;
}
track = 1;
}
} else {
check_wp();
if (raw_cmd->track != DRS->track &&
(raw_cmd->flags & FD_RAW_NEED_SEEK))
track = raw_cmd->track;
else {
setup_rw_floppy();
return;
}
}
do_floppy = seek_interrupt;
output_byte(FD_SEEK);
output_byte(UNIT(current_drive));
if (output_byte(track) < 0) {
reset_fdc();
return;
}
debugt(__func__, "");
}
static void recal_interrupt(void)
{
debugt(__func__, "");
if (inr != 2)
FDCS->reset = 1;
else if (ST0 & ST0_ECE) {
switch (DRS->track) {
case NEED_1_RECAL:
debugt(__func__, "need 1 recal");
/* after a second recalibrate, we still haven't
* reached track 0. Probably no drive. Raise an
* error, as failing immediately might upset
* computers possessed by the Devil :-) */
cont->error();
cont->redo();
return;
case NEED_2_RECAL:
debugt(__func__, "need 2 recal");
/* If we already did a recalibrate,
* and we are not at track 0, this
* means we have moved. (The only way
* not to move at recalibration is to
* be already at track 0.) Clear the
* new change flag */
debug_dcl(DP->flags,
"clearing NEWCHANGE flag because of second recalibrate\n");
clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
DRS->select_date = jiffies;
/* fall through */
default:
debugt(__func__, "default");
/* Recalibrate moves the head by at
* most 80 steps. If after one
* recalibrate we don't have reached
* track 0, this might mean that we
* started beyond track 80. Try
* again. */
DRS->track = NEED_1_RECAL;
break;
}
} else
DRS->track = ST1;
floppy_ready();
}
static void print_result(char *message, int inr)
{
int i;
DPRINT("%s ", message);
if (inr >= 0)
for (i = 0; i < inr; i++)
pr_cont("repl[%d]=%x ", i, reply_buffer[i]);
pr_cont("\n");
}
/* interrupt handler. Note that this can be called externally on the Sparc */
irqreturn_t floppy_interrupt(int irq, void *dev_id)
{
int do_print;
unsigned long f;
void (*handler)(void) = do_floppy;
lasthandler = handler;
interruptjiffies = jiffies;
f = claim_dma_lock();
fd_disable_dma();
release_dma_lock(f);
do_floppy = NULL;
if (fdc >= N_FDC || FDCS->address == -1) {
/* we don't even know which FDC is the culprit */
pr_info("DOR0=%x\n", fdc_state[0].dor);
pr_info("floppy interrupt on bizarre fdc %d\n", fdc);
pr_info("handler=%ps\n", handler);
is_alive(__func__, "bizarre fdc");
return IRQ_NONE;
}
FDCS->reset = 0;
/* We have to clear the reset flag here, because apparently on boxes
* with level triggered interrupts (PS/2, Sparc, ...), it is needed to
* emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the
* emission of the SENSEI's.
* It is OK to emit floppy commands because we are in an interrupt
* handler here, and thus we have to fear no interference of other
* activity.
*/
do_print = !handler && print_unex && initialized;
inr = result();
if (do_print)
print_result("unexpected interrupt", inr);
if (inr == 0) {
int max_sensei = 4;
do {
output_byte(FD_SENSEI);
inr = result();
if (do_print)
print_result("sensei", inr);
max_sensei--;
} while ((ST0 & 0x83) != UNIT(current_drive) &&
inr == 2 && max_sensei);
}
if (!handler) {
FDCS->reset = 1;
return IRQ_NONE;
}
schedule_bh(handler);
is_alive(__func__, "normal interrupt end");
/* FIXME! Was it really for us? */
return IRQ_HANDLED;
}
static void recalibrate_floppy(void)
{
debugt(__func__, "");
do_floppy = recal_interrupt;
output_byte(FD_RECALIBRATE);
if (output_byte(UNIT(current_drive)) < 0)
reset_fdc();
}
/*
* Must do 4 FD_SENSEIs after reset because of ``drive polling''.
*/
static void reset_interrupt(void)
{
debugt(__func__, "");
result(); /* get the status ready for set_fdc */
if (FDCS->reset) {
pr_info("reset set in interrupt, calling %ps\n", cont->error);
cont->error(); /* a reset just after a reset. BAD! */
}
cont->redo();
}
/*
* reset is done by pulling bit 2 of DOR low for a while (old FDCs),
* or by setting the self clearing bit 7 of STATUS (newer FDCs)
*/
static void reset_fdc(void)
{
unsigned long flags;
do_floppy = reset_interrupt;
FDCS->reset = 0;
reset_fdc_info(0);
/* Pseudo-DMA may intercept 'reset finished' interrupt. */
/* Irrelevant for systems with true DMA (i386). */
flags = claim_dma_lock();
fd_disable_dma();
release_dma_lock(flags);
if (FDCS->version >= FDC_82072A)
fd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS);
else {
fd_outb(FDCS->dor & ~0x04, FD_DOR);
udelay(FD_RESET_DELAY);
fd_outb(FDCS->dor, FD_DOR);
}
}
static void show_floppy(void)
{
int i;
pr_info("\n");
pr_info("floppy driver state\n");
pr_info("-------------------\n");
pr_info("now=%lu last interrupt=%lu diff=%lu last called handler=%ps\n",
jiffies, interruptjiffies, jiffies - interruptjiffies,
lasthandler);
pr_info("timeout_message=%s\n", timeout_message);
pr_info("last output bytes:\n");
for (i = 0; i < OLOGSIZE; i++)
pr_info("%2x %2x %lu\n",
output_log[(i + output_log_pos) % OLOGSIZE].data,
output_log[(i + output_log_pos) % OLOGSIZE].status,
output_log[(i + output_log_pos) % OLOGSIZE].jiffies);
pr_info("last result at %lu\n", resultjiffies);
pr_info("last redo_fd_request at %lu\n", lastredo);
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE, 16, 1,
reply_buffer, resultsize, true);
pr_info("status=%x\n", fd_inb(FD_STATUS));
pr_info("fdc_busy=%lu\n", fdc_busy);
if (do_floppy)
pr_info("do_floppy=%ps\n", do_floppy);
if (work_pending(&floppy_work))
pr_info("floppy_work.func=%ps\n", floppy_work.func);
if (delayed_work_pending(&fd_timer))
pr_info("delayed work.function=%p expires=%ld\n",
fd_timer.work.func,
fd_timer.timer.expires - jiffies);
if (delayed_work_pending(&fd_timeout))
pr_info("timer_function=%p expires=%ld\n",
fd_timeout.work.func,
fd_timeout.timer.expires - jiffies);
pr_info("cont=%p\n", cont);
pr_info("current_req=%p\n", current_req);
pr_info("command_status=%d\n", command_status);
pr_info("\n");
}
static void floppy_shutdown(struct work_struct *arg)
{
unsigned long flags;
if (initialized)
show_floppy();
cancel_activity();
flags = claim_dma_lock();
fd_disable_dma();
release_dma_lock(flags);
/* avoid dma going to a random drive after shutdown */
if (initialized)
DPRINT("floppy timeout called\n");
FDCS->reset = 1;
if (cont) {
cont->done(0);
cont->redo(); /* this will recall reset when needed */
} else {
pr_info("no cont in shutdown!\n");
process_fd_request();
}
is_alive(__func__, "");
}
/* start motor, check media-changed condition and write protection */
static int start_motor(void (*function)(void))
{
int mask;
int data;
mask = 0xfc;
data = UNIT(current_drive);
if (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) {
if (!(FDCS->dor & (0x10 << UNIT(current_drive)))) {
set_debugt();
/* no read since this drive is running */
DRS->first_read_date = 0;
/* note motor start time if motor is not yet running */
DRS->spinup_date = jiffies;
data |= (0x10 << UNIT(current_drive));
}
} else if (FDCS->dor & (0x10 << UNIT(current_drive)))
mask &= ~(0x10 << UNIT(current_drive));
/* starts motor and selects floppy */
del_timer(motor_off_timer + current_drive);
set_dor(fdc, mask, data);
/* wait_for_completion also schedules reset if needed. */
return fd_wait_for_completion(DRS->select_date + DP->select_delay,
function);
}
static void floppy_ready(void)
{
if (FDCS->reset) {
reset_fdc();
return;
}
if (start_motor(floppy_ready))
return;
if (fdc_dtr())
return;
debug_dcl(DP->flags, "calling disk change from floppy_ready\n");
if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) &&
disk_change(current_drive) && !DP->select_delay)
twaddle(); /* this clears the dcl on certain
* drive/controller combinations */
#ifdef fd_chose_dma_mode
if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) {
unsigned long flags = claim_dma_lock();
fd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length);
release_dma_lock(flags);
}
#endif
if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) {
perpendicular_mode();
fdc_specify(); /* must be done here because of hut, hlt ... */
seek_floppy();
} else {
if ((raw_cmd->flags & FD_RAW_READ) ||
(raw_cmd->flags & FD_RAW_WRITE))
fdc_specify();
setup_rw_floppy();
}
}
static void floppy_start(void)
{
reschedule_timeout(current_reqD, "floppy start");
scandrives();
debug_dcl(DP->flags, "setting NEWCHANGE in floppy_start\n");
set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
floppy_ready();
}
/*
* ========================================================================
* here ends the bottom half. Exported routines are:
* floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc,
* start_motor, reset_fdc, reset_fdc_info, interpret_errors.
* Initialization also uses output_byte, result, set_dor, floppy_interrupt
* and set_dor.
* ========================================================================
*/
/*
* General purpose continuations.
* ==============================
*/
static void do_wakeup(void)
{
reschedule_timeout(MAXTIMEOUT, "do wakeup");
cont = NULL;
command_status += 2;
wake_up(&command_done);
}
static const struct cont_t wakeup_cont = {
.interrupt = empty,
.redo = do_wakeup,
.error = empty,
.done = (done_f)empty
};
static const struct cont_t intr_cont = {
.interrupt = empty,
.redo = process_fd_request,
.error = empty,
.done = (done_f)empty
};
static int wait_til_done(void (*handler)(void), bool interruptible)
{
int ret;
schedule_bh(handler);
if (interruptible)
wait_event_interruptible(command_done, command_status >= 2);
else
wait_event(command_done, command_status >= 2);
if (command_status < 2) {
cancel_activity();
cont = &intr_cont;
reset_fdc();
return -EINTR;
}
if (FDCS->reset)
command_status = FD_COMMAND_ERROR;
if (command_status == FD_COMMAND_OKAY)
ret = 0;
else
ret = -EIO;
command_status = FD_COMMAND_NONE;
return ret;
}
static void generic_done(int result)
{
command_status = result;
cont = &wakeup_cont;
}
static void generic_success(void)
{
cont->done(1);
}
static void generic_failure(void)
{
cont->done(0);
}
static void success_and_wakeup(void)
{
generic_success();
cont->redo();
}
/*
* formatting and rw support.
* ==========================
*/
static int next_valid_format(void)
{
int probed_format;
probed_format = DRS->probed_format;
while (1) {
if (probed_format >= 8 || !DP->autodetect[probed_format]) {
DRS->probed_format = 0;
return 1;
}
if (floppy_type[DP->autodetect[probed_format]].sect) {
DRS->probed_format = probed_format;
return 0;
}
probed_format++;
}
}
static void bad_flp_intr(void)
{
int err_count;
if (probing) {
DRS->probed_format++;
if (!next_valid_format())
return;
}
err_count = ++(*errors);
INFBOUND(DRWE->badness, err_count);
if (err_count > DP->max_errors.abort)
cont->done(0);
if (err_count > DP->max_errors.reset)
FDCS->reset = 1;
else if (err_count > DP->max_errors.recal)
DRS->track = NEED_2_RECAL;
}
static void set_floppy(int drive)
{
int type = ITYPE(UDRS->fd_device);
if (type)
_floppy = floppy_type + type;
else
_floppy = current_type[drive];
}
/*
* formatting support.
* ===================
*/
static void format_interrupt(void)
{
switch (interpret_errors()) {
case 1:
cont->error();
case 2:
break;
case 0:
cont->done(1);
}
cont->redo();
}
#define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1))
#define CT(x) ((x) | 0xc0)
static void setup_format_params(int track)
{
int n;
int il;
int count;
int head_shift;
int track_shift;
struct fparm {
unsigned char track, head, sect, size;
} *here = (struct fparm *)floppy_track_buffer;
raw_cmd = &default_raw_cmd;
raw_cmd->track = track;
raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |
FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);
raw_cmd->rate = _floppy->rate & 0x43;
raw_cmd->cmd_count = NR_F;
COMMAND = FM_MODE(_floppy, FD_FORMAT);
DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);
F_SIZECODE = FD_SIZECODE(_floppy);
F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;
F_GAP = _floppy->fmt_gap;
F_FILL = FD_FILL_BYTE;
raw_cmd->kernel_data = floppy_track_buffer;
raw_cmd->length = 4 * F_SECT_PER_TRACK;
if (!F_SECT_PER_TRACK)
return;
/* allow for about 30ms for data transport per track */
head_shift = (F_SECT_PER_TRACK + 5) / 6;
/* a ``cylinder'' is two tracks plus a little stepping time */
track_shift = 2 * head_shift + 3;
/* position of logical sector 1 on this track */
n = (track_shift * format_req.track + head_shift * format_req.head)
% F_SECT_PER_TRACK;
/* determine interleave */
il = 1;
if (_floppy->fmt_gap < 0x22)
il++;
/* initialize field */
for (count = 0; count < F_SECT_PER_TRACK; ++count) {
here[count].track = format_req.track;
here[count].head = format_req.head;
here[count].sect = 0;
here[count].size = F_SIZECODE;
}
/* place logical sectors */
for (count = 1; count <= F_SECT_PER_TRACK; ++count) {
here[n].sect = count;
n = (n + il) % F_SECT_PER_TRACK;
if (here[n].sect) { /* sector busy, find next free sector */
++n;
if (n >= F_SECT_PER_TRACK) {
n -= F_SECT_PER_TRACK;
while (here[n].sect)
++n;
}
}
}
if (_floppy->stretch & FD_SECTBASEMASK) {
for (count = 0; count < F_SECT_PER_TRACK; count++)
here[count].sect += FD_SECTBASE(_floppy) - 1;
}
}
static void redo_format(void)
{
buffer_track = -1;
setup_format_params(format_req.track << STRETCH(_floppy));
floppy_start();
debugt(__func__, "queue format request");
}
static const struct cont_t format_cont = {
.interrupt = format_interrupt,
.redo = redo_format,
.error = bad_flp_intr,
.done = generic_done
};
static int do_format(int drive, struct format_descr *tmp_format_req)
{
int ret;
if (lock_fdc(drive))
return -EINTR;
set_floppy(drive);
if (!_floppy ||
_floppy->track > DP->tracks ||
tmp_format_req->track >= _floppy->track ||
tmp_format_req->head >= _floppy->head ||
(_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) ||
!_floppy->fmt_gap) {
process_fd_request();
return -EINVAL;
}
format_req = *tmp_format_req;
format_errors = 0;
cont = &format_cont;
errors = &format_errors;
ret = wait_til_done(redo_format, true);
if (ret == -EINTR)
return -EINTR;
process_fd_request();
return ret;
}
/*
* Buffer read/write and support
* =============================
*/
static void floppy_end_request(struct request *req, blk_status_t error)
{
unsigned int nr_sectors = current_count_sectors;
unsigned int drive = (unsigned long)req->rq_disk->private_data;
/* current_count_sectors can be zero if transfer failed */
if (error)
nr_sectors = blk_rq_cur_sectors(req);
if (blk_update_request(req, error, nr_sectors << 9))
return;
__blk_mq_end_request(req, error);
/* We're done with the request */
floppy_off(drive);
current_req = NULL;
}
/* new request_done. Can handle physical sectors which are smaller than a
* logical buffer */
static void request_done(int uptodate)
{
struct request *req = current_req;
int block;
char msg[sizeof("request done ") + sizeof(int) * 3];
probing = 0;
snprintf(msg, sizeof(msg), "request done %d", uptodate);
reschedule_timeout(MAXTIMEOUT, msg);
if (!req) {
pr_info("floppy.c: no request in request_done\n");
return;
}
if (uptodate) {
/* maintain values for invalidation on geometry
* change */
block = current_count_sectors + blk_rq_pos(req);
INFBOUND(DRS->maxblock, block);
if (block > _floppy->sect)
DRS->maxtrack = 1;
floppy_end_request(req, 0);
} else {
if (rq_data_dir(req) == WRITE) {
/* record write error information */
DRWE->write_errors++;
if (DRWE->write_errors == 1) {
DRWE->first_error_sector = blk_rq_pos(req);
DRWE->first_error_generation = DRS->generation;
}
DRWE->last_error_sector = blk_rq_pos(req);
DRWE->last_error_generation = DRS->generation;
}
floppy_end_request(req, BLK_STS_IOERR);
}
}
/* Interrupt handler evaluating the result of the r/w operation */
static void rw_interrupt(void)
{
int eoc;
int ssize;
int heads;
int nr_sectors;
if (R_HEAD >= 2) {
/* some Toshiba floppy controllers occasionnally seem to
* return bogus interrupts after read/write operations, which
* can be recognized by a bad head number (>= 2) */
return;
}
if (!DRS->first_read_date)
DRS->first_read_date = jiffies;
nr_sectors = 0;
ssize = DIV_ROUND_UP(1 << SIZECODE, 4);
if (ST1 & ST1_EOC)
eoc = 1;
else
eoc = 0;
if (COMMAND & 0x80)
heads = 2;
else
heads = 1;
nr_sectors = (((R_TRACK - TRACK) * heads +
R_HEAD - HEAD) * SECT_PER_TRACK +
R_SECTOR - SECTOR + eoc) << SIZECODE >> 2;
if (nr_sectors / ssize >
DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) {
DPRINT("long rw: %x instead of %lx\n",
nr_sectors, current_count_sectors);
pr_info("rs=%d s=%d\n", R_SECTOR, SECTOR);
pr_info("rh=%d h=%d\n", R_HEAD, HEAD);
pr_info("rt=%d t=%d\n", R_TRACK, TRACK);
pr_info("heads=%d eoc=%d\n", heads, eoc);
pr_info("spt=%d st=%d ss=%d\n",
SECT_PER_TRACK, fsector_t, ssize);
pr_info("in_sector_offset=%d\n", in_sector_offset);
}
nr_sectors -= in_sector_offset;
INFBOUND(nr_sectors, 0);
SUPBOUND(current_count_sectors, nr_sectors);
switch (interpret_errors()) {
case 2:
cont->redo();
return;
case 1:
if (!current_count_sectors) {
cont->error();
cont->redo();
return;
}
break;
case 0:
if (!current_count_sectors) {
cont->redo();
return;
}
current_type[current_drive] = _floppy;
floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
break;
}
if (probing) {
if (DP->flags & FTD_MSG)
DPRINT("Auto-detected floppy type %s in fd%d\n",
_floppy->name, current_drive);
current_type[current_drive] = _floppy;
floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
probing = 0;
}
if (CT(COMMAND) != FD_READ ||
raw_cmd->kernel_data == bio_data(current_req->bio)) {
/* transfer directly from buffer */
cont->done(1);
} else if (CT(COMMAND) == FD_READ) {
buffer_track = raw_cmd->track;
buffer_drive = current_drive;
INFBOUND(buffer_max, nr_sectors + fsector_t);
}
cont->redo();
}
/* Compute maximal contiguous buffer size. */
static int buffer_chain_size(void)
{
struct bio_vec bv;
int size;
struct req_iterator iter;
char *base;
base = bio_data(current_req->bio);
size = 0;
rq_for_each_segment(bv, current_req, iter) {
if (page_address(bv.bv_page) + bv.bv_offset != base + size)
break;
size += bv.bv_len;
}
return size >> 9;
}
/* Compute the maximal transfer size */
static int transfer_size(int ssize, int max_sector, int max_size)
{
SUPBOUND(max_sector, fsector_t + max_size);
/* alignment */
max_sector -= (max_sector % _floppy->sect) % ssize;
/* transfer size, beginning not aligned */
current_count_sectors = max_sector - fsector_t;
return max_sector;
}
/*
* Move data from/to the track buffer to/from the buffer cache.
*/
static void copy_buffer(int ssize, int max_sector, int max_sector_2)
{
int remaining; /* number of transferred 512-byte sectors */
struct bio_vec bv;
char *buffer;
char *dma_buffer;
int size;
struct req_iterator iter;
max_sector = transfer_size(ssize,
min(max_sector, max_sector_2),
blk_rq_sectors(current_req));
if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&
buffer_max > fsector_t + blk_rq_sectors(current_req))
current_count_sectors = min_t(int, buffer_max - fsector_t,
blk_rq_sectors(current_req));
remaining = current_count_sectors << 9;
if (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) {
DPRINT("in copy buffer\n");
pr_info("current_count_sectors=%ld\n", current_count_sectors);
pr_info("remaining=%d\n", remaining >> 9);
pr_info("current_req->nr_sectors=%u\n",
blk_rq_sectors(current_req));
pr_info("current_req->current_nr_sectors=%u\n",
blk_rq_cur_sectors(current_req));
pr_info("max_sector=%d\n", max_sector);
pr_info("ssize=%d\n", ssize);
}
buffer_max = max(max_sector, buffer_max);
dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9);
size = blk_rq_cur_bytes(current_req);
rq_for_each_segment(bv, current_req, iter) {
if (!remaining)
break;
size = bv.bv_len;
SUPBOUND(size, remaining);
buffer = page_address(bv.bv_page) + bv.bv_offset;
if (dma_buffer + size >
floppy_track_buffer + (max_buffer_sectors << 10) ||
dma_buffer < floppy_track_buffer) {
DPRINT("buffer overrun in copy buffer %d\n",
(int)((floppy_track_buffer - dma_buffer) >> 9));
pr_info("fsector_t=%d buffer_min=%d\n",
fsector_t, buffer_min);
pr_info("current_count_sectors=%ld\n",
current_count_sectors);
if (CT(COMMAND) == FD_READ)
pr_info("read\n");
if (CT(COMMAND) == FD_WRITE)
pr_info("write\n");
break;
}
if (((unsigned long)buffer) % 512)
DPRINT("%p buffer not aligned\n", buffer);
if (CT(COMMAND) == FD_READ)
memcpy(buffer, dma_buffer, size);
else
memcpy(dma_buffer, buffer, size);
remaining -= size;
dma_buffer += size;
}
if (remaining) {
if (remaining > 0)
max_sector -= remaining >> 9;
DPRINT("weirdness: remaining %d\n", remaining >> 9);
}
}
/* work around a bug in pseudo DMA
* (on some FDCs) pseudo DMA does not stop when the CPU stops
* sending data. Hence we need a different way to signal the
* transfer length: We use SECT_PER_TRACK. Unfortunately, this
* does not work with MT, hence we can only transfer one head at
* a time
*/
static void virtualdmabug_workaround(void)
{
int hard_sectors;
int end_sector;
if (CT(COMMAND) == FD_WRITE) {
COMMAND &= ~0x80; /* switch off multiple track mode */
hard_sectors = raw_cmd->length >> (7 + SIZECODE);
end_sector = SECTOR + hard_sectors - 1;
if (end_sector > SECT_PER_TRACK) {
pr_info("too many sectors %d > %d\n",
end_sector, SECT_PER_TRACK);
return;
}
SECT_PER_TRACK = end_sector;
/* make sure SECT_PER_TRACK
* points to end of transfer */
}
}
/*
* Formulate a read/write request.
* this routine decides where to load the data (directly to buffer, or to
* tmp floppy area), how much data to load (the size of the buffer, the whole
* track, or a single sector)
* All floppy_track_buffer handling goes in here. If we ever add track buffer
* allocation on the fly, it should be done here. No other part should need
* modification.
*/
static int make_raw_rw_request(void)
{
int aligned_sector_t;
int max_sector;
int max_size;
int tracksize;
int ssize;
if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n"))
return 0;
set_fdc((long)current_req->rq_disk->private_data);
raw_cmd = &default_raw_cmd;
raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK;
raw_cmd->cmd_count = NR_RW;
if (rq_data_dir(current_req) == READ) {
raw_cmd->flags |= FD_RAW_READ;
COMMAND = FM_MODE(_floppy, FD_READ);
} else if (rq_data_dir(current_req) == WRITE) {
raw_cmd->flags |= FD_RAW_WRITE;
COMMAND = FM_MODE(_floppy, FD_WRITE);
} else {
DPRINT("%s: unknown command\n", __func__);
return 0;
}
max_sector = _floppy->sect * _floppy->head;
TRACK = (int)blk_rq_pos(current_req) / max_sector;
fsector_t = (int)blk_rq_pos(current_req) % max_sector;
if (_floppy->track && TRACK >= _floppy->track) {
if (blk_rq_cur_sectors(current_req) & 1) {
current_count_sectors = 1;
return 1;
} else
return 0;
}
HEAD = fsector_t / _floppy->sect;
if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) ||
test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) &&
fsector_t < _floppy->sect)
max_sector = _floppy->sect;
/* 2M disks have phantom sectors on the first track */
if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) {
max_sector = 2 * _floppy->sect / 3;
if (fsector_t >= max_sector) {
current_count_sectors =
min_t(int, _floppy->sect - fsector_t,
blk_rq_sectors(current_req));
return 1;
}
SIZECODE = 2;
} else
SIZECODE = FD_SIZECODE(_floppy);
raw_cmd->rate = _floppy->rate & 0x43;
if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2)
raw_cmd->rate = 1;
if (SIZECODE)
SIZECODE2 = 0xff;
else
SIZECODE2 = 0x80;
raw_cmd->track = TRACK << STRETCH(_floppy);
DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD);
GAP = _floppy->gap;
ssize = DIV_ROUND_UP(1 << SIZECODE, 4);
SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;
SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) +
FD_SECTBASE(_floppy);
/* tracksize describes the size which can be filled up with sectors
* of size ssize.
*/
tracksize = _floppy->sect - _floppy->sect % ssize;
if (tracksize < _floppy->sect) {
SECT_PER_TRACK++;
if (tracksize <= fsector_t % _floppy->sect)
SECTOR--;
/* if we are beyond tracksize, fill up using smaller sectors */
while (tracksize <= fsector_t % _floppy->sect) {
while (tracksize + ssize > _floppy->sect) {
SIZECODE--;
ssize >>= 1;
}
SECTOR++;
SECT_PER_TRACK++;
tracksize += ssize;
}
max_sector = HEAD * _floppy->sect + tracksize;
} else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {
max_sector = _floppy->sect;
} else if (!HEAD && CT(COMMAND) == FD_WRITE) {
/* for virtual DMA bug workaround */
max_sector = _floppy->sect;
}
in_sector_offset = (fsector_t % _floppy->sect) % ssize;
aligned_sector_t = fsector_t - in_sector_offset;
max_size = blk_rq_sectors(current_req);
if ((raw_cmd->track == buffer_track) &&
(current_drive == buffer_drive) &&
(fsector_t >= buffer_min) && (fsector_t < buffer_max)) {
/* data already in track buffer */
if (CT(COMMAND) == FD_READ) {
copy_buffer(1, max_sector, buffer_max);
return 1;
}
} else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) {
if (CT(COMMAND) == FD_WRITE) {
unsigned int sectors;
sectors = fsector_t + blk_rq_sectors(current_req);
if (sectors > ssize && sectors < ssize + ssize)
max_size = ssize + ssize;
else
max_size = ssize;
}
raw_cmd->flags &= ~FD_RAW_WRITE;
raw_cmd->flags |= FD_RAW_READ;
COMMAND = FM_MODE(_floppy, FD_READ);
} else if ((unsigned long)bio_data(current_req->bio) < MAX_DMA_ADDRESS) {
unsigned long dma_limit;
int direct, indirect;
indirect =
transfer_size(ssize, max_sector,
max_buffer_sectors * 2) - fsector_t;
/*
* Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide
* on a 64 bit machine!
*/
max_size = buffer_chain_size();
dma_limit = (MAX_DMA_ADDRESS -
((unsigned long)bio_data(current_req->bio))) >> 9;
if ((unsigned long)max_size > dma_limit)
max_size = dma_limit;
/* 64 kb boundaries */
if (CROSS_64KB(bio_data(current_req->bio), max_size << 9))
max_size = (K_64 -
((unsigned long)bio_data(current_req->bio)) %
K_64) >> 9;
direct = transfer_size(ssize, max_sector, max_size) - fsector_t;
/*
* We try to read tracks, but if we get too many errors, we
* go back to reading just one sector at a time.
*
* This means we should be able to read a sector even if there
* are other bad sectors on this track.
*/
if (!direct ||
(indirect * 2 > direct * 3 &&
*errors < DP->max_errors.read_track &&
((!probing ||
(DP->read_track & (1 << DRS->probed_format)))))) {
max_size = blk_rq_sectors(current_req);
} else {
raw_cmd->kernel_data = bio_data(current_req->bio);
raw_cmd->length = current_count_sectors << 9;
if (raw_cmd->length == 0) {
DPRINT("%s: zero dma transfer attempted\n", __func__);
DPRINT("indirect=%d direct=%d fsector_t=%d\n",
indirect, direct, fsector_t);
return 0;
}
virtualdmabug_workaround();
return 2;
}
}
if (CT(COMMAND) == FD_READ)
max_size = max_sector; /* unbounded */
/* claim buffer track if needed */
if (buffer_track != raw_cmd->track || /* bad track */
buffer_drive != current_drive || /* bad drive */
fsector_t > buffer_max ||
fsector_t < buffer_min ||
((CT(COMMAND) == FD_READ ||
(!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) &&
max_sector > 2 * max_buffer_sectors + buffer_min &&
max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) {
/* not enough space */
buffer_track = -1;
buffer_drive = current_drive;
buffer_max = buffer_min = aligned_sector_t;
}
raw_cmd->kernel_data = floppy_track_buffer +
((aligned_sector_t - buffer_min) << 9);
if (CT(COMMAND) == FD_WRITE) {
/* copy write buffer to track buffer.
* if we get here, we know that the write
* is either aligned or the data already in the buffer
* (buffer will be overwritten) */
if (in_sector_offset && buffer_track == -1)
DPRINT("internal error offset !=0 on write\n");
buffer_track = raw_cmd->track;
buffer_drive = current_drive;
copy_buffer(ssize, max_sector,
2 * max_buffer_sectors + buffer_min);
} else
transfer_size(ssize, max_sector,
2 * max_buffer_sectors + buffer_min -
aligned_sector_t);
/* round up current_count_sectors to get dma xfer size */
raw_cmd->length = in_sector_offset + current_count_sectors;
raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1;
raw_cmd->length <<= 9;
if ((raw_cmd->length < current_count_sectors << 9) ||
(raw_cmd->kernel_data != bio_data(current_req->bio) &&
CT(COMMAND) == FD_WRITE &&
(aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||
aligned_sector_t < buffer_min)) ||
raw_cmd->length % (128 << SIZECODE) ||
raw_cmd->length <= 0 || current_count_sectors <= 0) {
DPRINT("fractionary current count b=%lx s=%lx\n",
raw_cmd->length, current_count_sectors);
if (raw_cmd->kernel_data != bio_data(current_req->bio))
pr_info("addr=%d, length=%ld\n",
(int)((raw_cmd->kernel_data -
floppy_track_buffer) >> 9),
current_count_sectors);
pr_info("st=%d ast=%d mse=%d msi=%d\n",
fsector_t, aligned_sector_t, max_sector, max_size);
pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE);
pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n",
COMMAND, SECTOR, HEAD, TRACK);
pr_info("buffer drive=%d\n", buffer_drive);
pr_info("buffer track=%d\n", buffer_track);
pr_info("buffer_min=%d\n", buffer_min);
pr_info("buffer_max=%d\n", buffer_max);
return 0;
}
if (raw_cmd->kernel_data != bio_data(current_req->bio)) {
if (raw_cmd->kernel_data < floppy_track_buffer ||
current_count_sectors < 0 ||
raw_cmd->length < 0 ||
raw_cmd->kernel_data + raw_cmd->length >
floppy_track_buffer + (max_buffer_sectors << 10)) {
DPRINT("buffer overrun in schedule dma\n");
pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n",
fsector_t, buffer_min, raw_cmd->length >> 9);
pr_info("current_count_sectors=%ld\n",
current_count_sectors);
if (CT(COMMAND) == FD_READ)
pr_info("read\n");
if (CT(COMMAND) == FD_WRITE)
pr_info("write\n");
return 0;
}
} else if (raw_cmd->length > blk_rq_bytes(current_req) ||
current_count_sectors > blk_rq_sectors(current_req)) {
DPRINT("buffer overrun in direct transfer\n");
return 0;
} else if (raw_cmd->length < current_count_sectors << 9) {
DPRINT("more sectors than bytes\n");
pr_info("bytes=%ld\n", raw_cmd->length >> 9);
pr_info("sectors=%ld\n", current_count_sectors);
}
if (raw_cmd->length == 0) {
DPRINT("zero dma transfer attempted from make_raw_request\n");
return 0;
}
virtualdmabug_workaround();
return 2;
}
static int set_next_request(void)
{
current_req = list_first_entry_or_null(&floppy_reqs, struct request,
queuelist);
if (current_req) {
current_req->error_count = 0;
list_del_init(¤t_req->queuelist);
}
return current_req != NULL;
}
static void redo_fd_request(void)
{
int drive;
int tmp;
lastredo = jiffies;
if (current_drive < N_DRIVE)
floppy_off(current_drive);
do_request:
if (!current_req) {
int pending;
spin_lock_irq(&floppy_lock);
pending = set_next_request();
spin_unlock_irq(&floppy_lock);
if (!pending) {
do_floppy = NULL;
unlock_fdc();
return;
}
}
drive = (long)current_req->rq_disk->private_data;
set_fdc(drive);
reschedule_timeout(current_reqD, "redo fd request");
set_floppy(drive);
raw_cmd = &default_raw_cmd;
raw_cmd->flags = 0;
if (start_motor(redo_fd_request))
return;
disk_change(current_drive);
if (test_bit(current_drive, &fake_change) ||
test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) {
DPRINT("disk absent or changed during operation\n");
request_done(0);
goto do_request;
}
if (!_floppy) { /* Autodetection */
if (!probing) {
DRS->probed_format = 0;
if (next_valid_format()) {
DPRINT("no autodetectable formats\n");
_floppy = NULL;
request_done(0);
goto do_request;
}
}
probing = 1;
_floppy = floppy_type + DP->autodetect[DRS->probed_format];
} else
probing = 0;
errors = &(current_req->error_count);
tmp = make_raw_rw_request();
if (tmp < 2) {
request_done(tmp);
goto do_request;
}
if (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags))
twaddle();
schedule_bh(floppy_start);
debugt(__func__, "queue fd request");
return;
}
static const struct cont_t rw_cont = {
.interrupt = rw_interrupt,
.redo = redo_fd_request,
.error = bad_flp_intr,
.done = request_done
};
static void process_fd_request(void)
{
cont = &rw_cont;
schedule_bh(redo_fd_request);
}
static blk_status_t floppy_queue_rq(struct blk_mq_hw_ctx *hctx,
const struct blk_mq_queue_data *bd)
{
blk_mq_start_request(bd->rq);
if (WARN(max_buffer_sectors == 0,
"VFS: %s called on non-open device\n", __func__))
return BLK_STS_IOERR;
if (WARN(atomic_read(&usage_count) == 0,
"warning: usage count=0, current_req=%p sect=%ld flags=%llx\n",
current_req, (long)blk_rq_pos(current_req),
(unsigned long long) current_req->cmd_flags))
return BLK_STS_IOERR;
spin_lock_irq(&floppy_lock);
list_add_tail(&bd->rq->queuelist, &floppy_reqs);
spin_unlock_irq(&floppy_lock);
if (test_and_set_bit(0, &fdc_busy)) {
/* fdc busy, this new request will be treated when the
current one is done */
is_alive(__func__, "old request running");
return BLK_STS_OK;
}
command_status = FD_COMMAND_NONE;
__reschedule_timeout(MAXTIMEOUT, "fd_request");
set_fdc(0);
process_fd_request();
is_alive(__func__, "");
return BLK_STS_OK;
}
static const struct cont_t poll_cont = {
.interrupt = success_and_wakeup,
.redo = floppy_ready,
.error = generic_failure,
.done = generic_done
};
static int poll_drive(bool interruptible, int flag)
{
/* no auto-sense, just clear dcl */
raw_cmd = &default_raw_cmd;
raw_cmd->flags = flag;
raw_cmd->track = 0;
raw_cmd->cmd_count = 0;
cont = &poll_cont;
debug_dcl(DP->flags, "setting NEWCHANGE in poll_drive\n");
set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
return wait_til_done(floppy_ready, interruptible);
}
/*
* User triggered reset
* ====================
*/
static void reset_intr(void)
{
pr_info("weird, reset interrupt called\n");
}
static const struct cont_t reset_cont = {
.interrupt = reset_intr,
.redo = success_and_wakeup,
.error = generic_failure,
.done = generic_done
};
static int user_reset_fdc(int drive, int arg, bool interruptible)
{
int ret;
if (lock_fdc(drive))
return -EINTR;
if (arg == FD_RESET_ALWAYS)
FDCS->reset = 1;
if (FDCS->reset) {
cont = &reset_cont;
ret = wait_til_done(reset_fdc, interruptible);
if (ret == -EINTR)
return -EINTR;
}
process_fd_request();
return 0;
}
/*
* Misc Ioctl's and support
* ========================
*/
static inline int fd_copyout(void __user *param, const void *address,
unsigned long size)
{
return copy_to_user(param, address, size) ? -EFAULT : 0;
}
static inline int fd_copyin(void __user *param, void *address,
unsigned long size)
{
return copy_from_user(address, param, size) ? -EFAULT : 0;
}
static const char *drive_name(int type, int drive)
{
struct floppy_struct *floppy;
if (type)
floppy = floppy_type + type;
else {
if (UDP->native_format)
floppy = floppy_type + UDP->native_format;
else
return "(null)";
}
if (floppy->name)
return floppy->name;
else
return "(null)";
}
/* raw commands */
static void raw_cmd_done(int flag)
{
int i;
if (!flag) {
raw_cmd->flags |= FD_RAW_FAILURE;
raw_cmd->flags |= FD_RAW_HARDFAILURE;
} else {
raw_cmd->reply_count = inr;
if (raw_cmd->reply_count > MAX_REPLIES)
raw_cmd->reply_count = 0;
for (i = 0; i < raw_cmd->reply_count; i++)
raw_cmd->reply[i] = reply_buffer[i];
if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
unsigned long flags;
flags = claim_dma_lock();
raw_cmd->length = fd_get_dma_residue();
release_dma_lock(flags);
}
if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&
(!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))
raw_cmd->flags |= FD_RAW_FAILURE;
if (disk_change(current_drive))
raw_cmd->flags |= FD_RAW_DISK_CHANGE;
else
raw_cmd->flags &= ~FD_RAW_DISK_CHANGE;
if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)
motor_off_callback(&motor_off_timer[current_drive]);
if (raw_cmd->next &&
(!(raw_cmd->flags & FD_RAW_FAILURE) ||
!(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&
((raw_cmd->flags & FD_RAW_FAILURE) ||
!(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) {
raw_cmd = raw_cmd->next;
return;
}
}
generic_done(flag);
}
static const struct cont_t raw_cmd_cont = {
.interrupt = success_and_wakeup,
.redo = floppy_start,
.error = generic_failure,
.done = raw_cmd_done
};
static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
struct floppy_raw_cmd cmd = *ptr;
cmd.next = NULL;
cmd.kernel_data = NULL;
ret = copy_to_user(param, &cmd, sizeof(cmd));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
static void raw_cmd_free(struct floppy_raw_cmd **ptr)
{
struct floppy_raw_cmd *next;
struct floppy_raw_cmd *this;
this = *ptr;
*ptr = NULL;
while (this) {
if (this->buffer_length) {
fd_dma_mem_free((unsigned long)this->kernel_data,
this->buffer_length);
this->buffer_length = 0;
}
next = this->next;
kfree(this);
this = next;
}
}
static int raw_cmd_copyin(int cmd, void __user *param,
struct floppy_raw_cmd **rcmd)
{
struct floppy_raw_cmd *ptr;
int ret;
int i;
*rcmd = NULL;
loop:
ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_KERNEL);
if (!ptr)
return -ENOMEM;
*rcmd = ptr;
ret = copy_from_user(ptr, param, sizeof(*ptr));
ptr->next = NULL;
ptr->buffer_length = 0;
ptr->kernel_data = NULL;
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if (ptr->cmd_count > 33)
/* the command may now also take up the space
* initially intended for the reply & the
* reply count. Needed for long 82078 commands
* such as RESTORE, which takes ... 17 command
* bytes. Murphy's law #137: When you reserve
* 16 bytes for a structure, you'll one day
* discover that you really need 17...
*/
return -EINVAL;
for (i = 0; i < 16; i++)
ptr->reply[i] = 0;
ptr->resultcode = 0;
if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
if (ptr->length <= 0)
return -EINVAL;
ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);
fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);
if (!ptr->kernel_data)
return -ENOMEM;
ptr->buffer_length = ptr->length;
}
if (ptr->flags & FD_RAW_WRITE) {
ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);
if (ret)
return ret;
}
if (ptr->flags & FD_RAW_MORE) {
rcmd = &(ptr->next);
ptr->rate &= 0x43;
goto loop;
}
return 0;
}
static int raw_cmd_ioctl(int cmd, void __user *param)
{
struct floppy_raw_cmd *my_raw_cmd;
int drive;
int ret2;
int ret;
if (FDCS->rawcmd <= 1)
FDCS->rawcmd = 1;
for (drive = 0; drive < N_DRIVE; drive++) {
if (FDC(drive) != fdc)
continue;
if (drive == current_drive) {
if (UDRS->fd_ref > 1) {
FDCS->rawcmd = 2;
break;
}
} else if (UDRS->fd_ref) {
FDCS->rawcmd = 2;
break;
}
}
if (FDCS->reset)
return -EIO;
ret = raw_cmd_copyin(cmd, param, &my_raw_cmd);
if (ret) {
raw_cmd_free(&my_raw_cmd);
return ret;
}
raw_cmd = my_raw_cmd;
cont = &raw_cmd_cont;
ret = wait_til_done(floppy_start, true);
debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n");
if (ret != -EINTR && FDCS->reset)
ret = -EIO;
DRS->track = NO_TRACK;
ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);
if (!ret)
ret = ret2;
raw_cmd_free(&my_raw_cmd);
return ret;
}
static int invalidate_drive(struct block_device *bdev)
{
/* invalidate the buffer track to force a reread */
set_bit((long)bdev->bd_disk->private_data, &fake_change);
process_fd_request();
check_disk_change(bdev);
return 0;
}
static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if ((int)g->sect <= 0 ||
(int)g->head <= 0 ||
/* check for overflow in max_sector */
(int)(g->sect * g->head) <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
/* handle obsolete ioctl's */
static unsigned int ioctl_table[] = {
FDCLRPRM,
FDSETPRM,
FDDEFPRM,
FDGETPRM,
FDMSGON,
FDMSGOFF,
FDFMTBEG,
FDFMTTRK,
FDFMTEND,
FDSETEMSGTRESH,
FDFLUSH,
FDSETMAXERRS,
FDGETMAXERRS,
FDGETDRVTYP,
FDSETDRVPRM,
FDGETDRVPRM,
FDGETDRVSTAT,
FDPOLLDRVSTAT,
FDRESET,
FDGETFDCSTAT,
FDWERRORCLR,
FDWERRORGET,
FDRAWCMD,
FDEJECT,
FDTWADDLE
};
static int normalize_ioctl(unsigned int *cmd, int *size)
{
int i;
for (i = 0; i < ARRAY_SIZE(ioctl_table); i++) {
if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) {
*size = _IOC_SIZE(*cmd);
*cmd = ioctl_table[i];
if (*size > _IOC_SIZE(*cmd)) {
pr_info("ioctl not yet supported\n");
return -EFAULT;
}
return 0;
}
}
return -EINVAL;
}
static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)
{
if (type)
*g = &floppy_type[type];
else {
if (lock_fdc(drive))
return -EINTR;
if (poll_drive(false, 0) == -EINTR)
return -EINTR;
process_fd_request();
*g = current_type[drive];
}
if (!*g)
return -ENODEV;
return 0;
}
static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
int drive = (long)bdev->bd_disk->private_data;
int type = ITYPE(drive_state[drive].fd_device);
struct floppy_struct *g;
int ret;
ret = get_floppy_geometry(drive, type, &g);
if (ret)
return ret;
geo->heads = g->head;
geo->sectors = g->sect;
geo->cylinders = g->track;
return 0;
}
static bool valid_floppy_drive_params(const short autodetect[8],
int native_format)
{
size_t floppy_type_size = ARRAY_SIZE(floppy_type);
size_t i = 0;
for (i = 0; i < 8; ++i) {
if (autodetect[i] < 0 ||
autodetect[i] >= floppy_type_size)
return false;
}
if (native_format < 0 || native_format >= floppy_type_size)
return false;
return true;
}
static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
unsigned long param)
{
int drive = (long)bdev->bd_disk->private_data;
int type = ITYPE(UDRS->fd_device);
int i;
int ret;
int size;
union inparam {
struct floppy_struct g; /* geometry */
struct format_descr f;
struct floppy_max_errors max_errors;
struct floppy_drive_params dp;
} inparam; /* parameters coming from user space */
const void *outparam; /* parameters passed back to user space */
/* convert compatibility eject ioctls into floppy eject ioctl.
* We do this in order to provide a means to eject floppy disks before
* installing the new fdutils package */
if (cmd == CDROMEJECT || /* CD-ROM eject */
cmd == 0x6470) { /* SunOS floppy eject */
DPRINT("obsolete eject ioctl\n");
DPRINT("please use floppycontrol --eject\n");
cmd = FDEJECT;
}
if (!((cmd & 0xff00) == 0x0200))
return -EINVAL;
/* convert the old style command into a new style command */
ret = normalize_ioctl(&cmd, &size);
if (ret)
return ret;
/* permission checks */
if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) ||
((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))
return -EPERM;
if (WARN_ON(size < 0 || size > sizeof(inparam)))
return -EINVAL;
/* copyin */
memset(&inparam, 0, sizeof(inparam));
if (_IOC_DIR(cmd) & _IOC_WRITE) {
ret = fd_copyin((void __user *)param, &inparam, size);
if (ret)
return ret;
}
switch (cmd) {
case FDEJECT:
if (UDRS->fd_ref != 1)
/* somebody else has this drive open */
return -EBUSY;
if (lock_fdc(drive))
return -EINTR;
/* do the actual eject. Fails on
* non-Sparc architectures */
ret = fd_eject(UNIT(drive));
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
set_bit(FD_VERIFY_BIT, &UDRS->flags);
process_fd_request();
return ret;
case FDCLRPRM:
if (lock_fdc(drive))
return -EINTR;
current_type[drive] = NULL;
floppy_sizes[drive] = MAX_DISK_SIZE << 1;
UDRS->keep_data = 0;
return invalidate_drive(bdev);
case FDSETPRM:
case FDDEFPRM:
return set_geometry(cmd, &inparam.g, drive, type, bdev);
case FDGETPRM:
ret = get_floppy_geometry(drive, type,
(struct floppy_struct **)&outparam);
if (ret)
return ret;
memcpy(&inparam.g, outparam,
offsetof(struct floppy_struct, name));
outparam = &inparam.g;
break;
case FDMSGON:
UDP->flags |= FTD_MSG;
return 0;
case FDMSGOFF:
UDP->flags &= ~FTD_MSG;
return 0;
case FDFMTBEG:
if (lock_fdc(drive))
return -EINTR;
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
ret = UDRS->flags;
process_fd_request();
if (ret & FD_VERIFY)
return -ENODEV;
if (!(ret & FD_DISK_WRITABLE))
return -EROFS;
return 0;
case FDFMTTRK:
if (UDRS->fd_ref != 1)
return -EBUSY;
return do_format(drive, &inparam.f);
case FDFMTEND:
case FDFLUSH:
if (lock_fdc(drive))
return -EINTR;
return invalidate_drive(bdev);
case FDSETEMSGTRESH:
UDP->max_errors.reporting = (unsigned short)(param & 0x0f);
return 0;
case FDGETMAXERRS:
outparam = &UDP->max_errors;
break;
case FDSETMAXERRS:
UDP->max_errors = inparam.max_errors;
break;
case FDGETDRVTYP:
outparam = drive_name(type, drive);
SUPBOUND(size, strlen((const char *)outparam) + 1);
break;
case FDSETDRVPRM:
if (!valid_floppy_drive_params(inparam.dp.autodetect,
inparam.dp.native_format))
return -EINVAL;
*UDP = inparam.dp;
break;
case FDGETDRVPRM:
outparam = UDP;
break;
case FDPOLLDRVSTAT:
if (lock_fdc(drive))
return -EINTR;
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
process_fd_request();
/* fall through */
case FDGETDRVSTAT:
outparam = UDRS;
break;
case FDRESET:
return user_reset_fdc(drive, (int)param, true);
case FDGETFDCSTAT:
outparam = UFDCS;
break;
case FDWERRORCLR:
memset(UDRWE, 0, sizeof(*UDRWE));
return 0;
case FDWERRORGET:
outparam = UDRWE;
break;
case FDRAWCMD:
if (type)
return -EINVAL;
if (lock_fdc(drive))
return -EINTR;
set_floppy(drive);
i = raw_cmd_ioctl(cmd, (void __user *)param);
if (i == -EINTR)
return -EINTR;
process_fd_request();
return i;
case FDTWADDLE:
if (lock_fdc(drive))
return -EINTR;
twaddle();
process_fd_request();
return 0;
default:
return -EINVAL;
}
if (_IOC_DIR(cmd) & _IOC_READ)
return fd_copyout((void __user *)param, outparam, size);
return 0;
}
static int fd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long param)
{
int ret;
mutex_lock(&floppy_mutex);
ret = fd_locked_ioctl(bdev, mode, cmd, param);
mutex_unlock(&floppy_mutex);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_floppy_drive_params {
char cmos;
compat_ulong_t max_dtr;
compat_ulong_t hlt;
compat_ulong_t hut;
compat_ulong_t srt;
compat_ulong_t spinup;
compat_ulong_t spindown;
unsigned char spindown_offset;
unsigned char select_delay;
unsigned char rps;
unsigned char tracks;
compat_ulong_t timeout;
unsigned char interleave_sect;
struct floppy_max_errors max_errors;
char flags;
char read_track;
short autodetect[8];
compat_int_t checkfreq;
compat_int_t native_format;
};
struct compat_floppy_drive_struct {
signed char flags;
compat_ulong_t spinup_date;
compat_ulong_t select_date;
compat_ulong_t first_read_date;
short probed_format;
short track;
short maxblock;
short maxtrack;
compat_int_t generation;
compat_int_t keep_data;
compat_int_t fd_ref;
compat_int_t fd_device;
compat_int_t last_checked;
compat_caddr_t dmabuf;
compat_int_t bufblocks;
};
struct compat_floppy_fdc_state {
compat_int_t spec1;
compat_int_t spec2;
compat_int_t dtr;
unsigned char version;
unsigned char dor;
compat_ulong_t address;
unsigned int rawcmd:2;
unsigned int reset:1;
unsigned int need_configure:1;
unsigned int perp_mode:2;
unsigned int has_fifo:1;
unsigned int driver_version;
unsigned char track[4];
};
struct compat_floppy_write_errors {
unsigned int write_errors;
compat_ulong_t first_error_sector;
compat_int_t first_error_generation;
compat_ulong_t last_error_sector;
compat_int_t last_error_generation;
compat_uint_t badness;
};
#define FDSETPRM32 _IOW(2, 0x42, struct compat_floppy_struct)
#define FDDEFPRM32 _IOW(2, 0x43, struct compat_floppy_struct)
#define FDSETDRVPRM32 _IOW(2, 0x90, struct compat_floppy_drive_params)
#define FDGETDRVPRM32 _IOR(2, 0x11, struct compat_floppy_drive_params)
#define FDGETDRVSTAT32 _IOR(2, 0x12, struct compat_floppy_drive_struct)
#define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct compat_floppy_drive_struct)
#define FDGETFDCSTAT32 _IOR(2, 0x15, struct compat_floppy_fdc_state)
#define FDWERRORGET32 _IOR(2, 0x17, struct compat_floppy_write_errors)
static int compat_set_geometry(struct block_device *bdev, fmode_t mode, unsigned int cmd,
struct compat_floppy_struct __user *arg)
{
struct floppy_struct v;
int drive, type;
int err;
BUILD_BUG_ON(offsetof(struct floppy_struct, name) !=
offsetof(struct compat_floppy_struct, name));
if (!(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL)))
return -EPERM;
memset(&v, 0, sizeof(struct floppy_struct));
if (copy_from_user(&v, arg, offsetof(struct floppy_struct, name)))
return -EFAULT;
mutex_lock(&floppy_mutex);
drive = (long)bdev->bd_disk->private_data;
type = ITYPE(UDRS->fd_device);
err = set_geometry(cmd == FDSETPRM32 ? FDSETPRM : FDDEFPRM,
&v, drive, type, bdev);
mutex_unlock(&floppy_mutex);
return err;
}
static int compat_get_prm(int drive,
struct compat_floppy_struct __user *arg)
{
struct compat_floppy_struct v;
struct floppy_struct *p;
int err;
memset(&v, 0, sizeof(v));
mutex_lock(&floppy_mutex);
err = get_floppy_geometry(drive, ITYPE(UDRS->fd_device), &p);
if (err) {
mutex_unlock(&floppy_mutex);
return err;
}
memcpy(&v, p, offsetof(struct floppy_struct, name));
mutex_unlock(&floppy_mutex);
if (copy_to_user(arg, &v, sizeof(struct compat_floppy_struct)))
return -EFAULT;
return 0;
}
static int compat_setdrvprm(int drive,
struct compat_floppy_drive_params __user *arg)
{
struct compat_floppy_drive_params v;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (copy_from_user(&v, arg, sizeof(struct compat_floppy_drive_params)))
return -EFAULT;
if (!valid_floppy_drive_params(v.autodetect, v.native_format))
return -EINVAL;
mutex_lock(&floppy_mutex);
UDP->cmos = v.cmos;
UDP->max_dtr = v.max_dtr;
UDP->hlt = v.hlt;
UDP->hut = v.hut;
UDP->srt = v.srt;
UDP->spinup = v.spinup;
UDP->spindown = v.spindown;
UDP->spindown_offset = v.spindown_offset;
UDP->select_delay = v.select_delay;
UDP->rps = v.rps;
UDP->tracks = v.tracks;
UDP->timeout = v.timeout;
UDP->interleave_sect = v.interleave_sect;
UDP->max_errors = v.max_errors;
UDP->flags = v.flags;
UDP->read_track = v.read_track;
memcpy(UDP->autodetect, v.autodetect, sizeof(v.autodetect));
UDP->checkfreq = v.checkfreq;
UDP->native_format = v.native_format;
mutex_unlock(&floppy_mutex);
return 0;
}
static int compat_getdrvprm(int drive,
struct compat_floppy_drive_params __user *arg)
{
struct compat_floppy_drive_params v;
memset(&v, 0, sizeof(struct compat_floppy_drive_params));
mutex_lock(&floppy_mutex);
v.cmos = UDP->cmos;
v.max_dtr = UDP->max_dtr;
v.hlt = UDP->hlt;
v.hut = UDP->hut;
v.srt = UDP->srt;
v.spinup = UDP->spinup;
v.spindown = UDP->spindown;
v.spindown_offset = UDP->spindown_offset;
v.select_delay = UDP->select_delay;
v.rps = UDP->rps;
v.tracks = UDP->tracks;
v.timeout = UDP->timeout;
v.interleave_sect = UDP->interleave_sect;
v.max_errors = UDP->max_errors;
v.flags = UDP->flags;
v.read_track = UDP->read_track;
memcpy(v.autodetect, UDP->autodetect, sizeof(v.autodetect));
v.checkfreq = UDP->checkfreq;
v.native_format = UDP->native_format;
mutex_unlock(&floppy_mutex);
if (copy_to_user(arg, &v, sizeof(struct compat_floppy_drive_params)))
return -EFAULT;
return 0;
}
static int compat_getdrvstat(int drive, bool poll,
struct compat_floppy_drive_struct __user *arg)
{
struct compat_floppy_drive_struct v;
memset(&v, 0, sizeof(struct compat_floppy_drive_struct));
mutex_lock(&floppy_mutex);
if (poll) {
if (lock_fdc(drive))
goto Eintr;
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
goto Eintr;
process_fd_request();
}
v.spinup_date = UDRS->spinup_date;
v.select_date = UDRS->select_date;
v.first_read_date = UDRS->first_read_date;
v.probed_format = UDRS->probed_format;
v.track = UDRS->track;
v.maxblock = UDRS->maxblock;
v.maxtrack = UDRS->maxtrack;
v.generation = UDRS->generation;
v.keep_data = UDRS->keep_data;
v.fd_ref = UDRS->fd_ref;
v.fd_device = UDRS->fd_device;
v.last_checked = UDRS->last_checked;
v.dmabuf = (uintptr_t)UDRS->dmabuf;
v.bufblocks = UDRS->bufblocks;
mutex_unlock(&floppy_mutex);
if (copy_to_user(arg, &v, sizeof(struct compat_floppy_drive_struct)))
return -EFAULT;
return 0;
Eintr:
mutex_unlock(&floppy_mutex);
return -EINTR;
}
static int compat_getfdcstat(int drive,
struct compat_floppy_fdc_state __user *arg)
{
struct compat_floppy_fdc_state v32;
struct floppy_fdc_state v;
mutex_lock(&floppy_mutex);
v = *UFDCS;
mutex_unlock(&floppy_mutex);
memset(&v32, 0, sizeof(struct compat_floppy_fdc_state));
v32.spec1 = v.spec1;
v32.spec2 = v.spec2;
v32.dtr = v.dtr;
v32.version = v.version;
v32.dor = v.dor;
v32.address = v.address;
v32.rawcmd = v.rawcmd;
v32.reset = v.reset;
v32.need_configure = v.need_configure;
v32.perp_mode = v.perp_mode;
v32.has_fifo = v.has_fifo;
v32.driver_version = v.driver_version;
memcpy(v32.track, v.track, 4);
if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_fdc_state)))
return -EFAULT;
return 0;
}
static int compat_werrorget(int drive,
struct compat_floppy_write_errors __user *arg)
{
struct compat_floppy_write_errors v32;
struct floppy_write_errors v;
memset(&v32, 0, sizeof(struct compat_floppy_write_errors));
mutex_lock(&floppy_mutex);
v = *UDRWE;
mutex_unlock(&floppy_mutex);
v32.write_errors = v.write_errors;
v32.first_error_sector = v.first_error_sector;
v32.first_error_generation = v.first_error_generation;
v32.last_error_sector = v.last_error_sector;
v32.last_error_generation = v.last_error_generation;
v32.badness = v.badness;
if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_write_errors)))
return -EFAULT;
return 0;
}
static int fd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
unsigned long param)
{
int drive = (long)bdev->bd_disk->private_data;
switch (cmd) {
case CDROMEJECT: /* CD-ROM eject */
case 0x6470: /* SunOS floppy eject */
case FDMSGON:
case FDMSGOFF:
case FDSETEMSGTRESH:
case FDFLUSH:
case FDWERRORCLR:
case FDEJECT:
case FDCLRPRM:
case FDFMTBEG:
case FDRESET:
case FDTWADDLE:
return fd_ioctl(bdev, mode, cmd, param);
case FDSETMAXERRS:
case FDGETMAXERRS:
case FDGETDRVTYP:
case FDFMTEND:
case FDFMTTRK:
case FDRAWCMD:
return fd_ioctl(bdev, mode, cmd,
(unsigned long)compat_ptr(param));
case FDSETPRM32:
case FDDEFPRM32:
return compat_set_geometry(bdev, mode, cmd, compat_ptr(param));
case FDGETPRM32:
return compat_get_prm(drive, compat_ptr(param));
case FDSETDRVPRM32:
return compat_setdrvprm(drive, compat_ptr(param));
case FDGETDRVPRM32:
return compat_getdrvprm(drive, compat_ptr(param));
case FDPOLLDRVSTAT32:
return compat_getdrvstat(drive, true, compat_ptr(param));
case FDGETDRVSTAT32:
return compat_getdrvstat(drive, false, compat_ptr(param));
case FDGETFDCSTAT32:
return compat_getfdcstat(drive, compat_ptr(param));
case FDWERRORGET32:
return compat_werrorget(drive, compat_ptr(param));
}
return -EINVAL;
}
#endif
static void __init config_types(void)
{
bool has_drive = false;
int drive;
/* read drive info out of physical CMOS */
drive = 0;
if (!UDP->cmos)
UDP->cmos = FLOPPY0_TYPE;
drive = 1;
if (!UDP->cmos)
UDP->cmos = FLOPPY1_TYPE;
/* FIXME: additional physical CMOS drive detection should go here */
for (drive = 0; drive < N_DRIVE; drive++) {
unsigned int type = UDP->cmos;
struct floppy_drive_params *params;
const char *name = NULL;
char temparea[32];
if (type < ARRAY_SIZE(default_drive_params)) {
params = &default_drive_params[type].params;
if (type) {
name = default_drive_params[type].name;
allowed_drive_mask |= 1 << drive;
} else
allowed_drive_mask &= ~(1 << drive);
} else {
params = &default_drive_params[0].params;
snprintf(temparea, sizeof(temparea),
"unknown type %d (usb?)", type);
name = temparea;
}
if (name) {
const char *prepend;
if (!has_drive) {
prepend = "";
has_drive = true;
pr_info("Floppy drive(s):");
} else {
prepend = ",";
}
pr_cont("%s fd%d is %s", prepend, drive, name);
}
*UDP = *params;
}
if (has_drive)
pr_cont("\n");
}
static void floppy_release(struct gendisk *disk, fmode_t mode)
{
int drive = (long)disk->private_data;
mutex_lock(&floppy_mutex);
mutex_lock(&open_lock);
if (!UDRS->fd_ref--) {
DPRINT("floppy_release with fd_ref == 0");
UDRS->fd_ref = 0;
}
if (!UDRS->fd_ref)
opened_bdev[drive] = NULL;
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
}
/*
* floppy_open check for aliasing (/dev/fd0 can be the same as
* /dev/PS0 etc), and disallows simultaneous access to the same
* drive with different device numbers.
*/
static int floppy_open(struct block_device *bdev, fmode_t mode)
{
int drive = (long)bdev->bd_disk->private_data;
int old_dev, new_dev;
int try;
int res = -EBUSY;
char *tmp;
mutex_lock(&floppy_mutex);
mutex_lock(&open_lock);
old_dev = UDRS->fd_device;
if (opened_bdev[drive] && opened_bdev[drive] != bdev)
goto out2;
if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) {
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
set_bit(FD_VERIFY_BIT, &UDRS->flags);
}
UDRS->fd_ref++;
opened_bdev[drive] = bdev;
res = -ENXIO;
if (!floppy_track_buffer) {
/* if opening an ED drive, reserve a big buffer,
* else reserve a small one */
if ((UDP->cmos == 6) || (UDP->cmos == 5))
try = 64; /* Only 48 actually useful */
else
try = 32; /* Only 24 actually useful */
tmp = (char *)fd_dma_mem_alloc(1024 * try);
if (!tmp && !floppy_track_buffer) {
try >>= 1; /* buffer only one side */
INFBOUND(try, 16);
tmp = (char *)fd_dma_mem_alloc(1024 * try);
}
if (!tmp && !floppy_track_buffer)
fallback_on_nodma_alloc(&tmp, 2048 * try);
if (!tmp && !floppy_track_buffer) {
DPRINT("Unable to allocate DMA memory\n");
goto out;
}
if (floppy_track_buffer) {
if (tmp)
fd_dma_mem_free((unsigned long)tmp, try * 1024);
} else {
buffer_min = buffer_max = -1;
floppy_track_buffer = tmp;
max_buffer_sectors = try;
}
}
new_dev = MINOR(bdev->bd_dev);
UDRS->fd_device = new_dev;
set_capacity(disks[drive], floppy_sizes[new_dev]);
if (old_dev != -1 && old_dev != new_dev) {
if (buffer_drive == drive)
buffer_track = -1;
}
if (UFDCS->rawcmd == 1)
UFDCS->rawcmd = 2;
if (!(mode & FMODE_NDELAY)) {
if (mode & (FMODE_READ|FMODE_WRITE)) {
UDRS->last_checked = 0;
clear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);
check_disk_change(bdev);
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags))
goto out;
if (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags))
goto out;
}
res = -EROFS;
if ((mode & FMODE_WRITE) &&
!test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags))
goto out;
}
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
return 0;
out:
UDRS->fd_ref--;
if (!UDRS->fd_ref)
opened_bdev[drive] = NULL;
out2:
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
return res;
}
/*
* Check if the disk has been changed or if a change has been faked.
*/
static unsigned int floppy_check_events(struct gendisk *disk,
unsigned int clearing)
{
int drive = (long)disk->private_data;
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags))
return DISK_EVENT_MEDIA_CHANGE;
if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) {
if (lock_fdc(drive))
return 0;
poll_drive(false, 0);
process_fd_request();
}
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
test_bit(drive, &fake_change) ||
drive_no_geom(drive))
return DISK_EVENT_MEDIA_CHANGE;
return 0;
}
/*
* This implements "read block 0" for floppy_revalidate().
* Needed for format autodetection, checking whether there is
* a disk in the drive, and whether that disk is writable.
*/
struct rb0_cbdata {
int drive;
struct completion complete;
};
static void floppy_rb0_cb(struct bio *bio)
{
struct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private;
int drive = cbdata->drive;
if (bio->bi_status) {
pr_info("floppy: error %d while reading block 0\n",
bio->bi_status);
set_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);
}
complete(&cbdata->complete);
}
static int __floppy_read_block_0(struct block_device *bdev, int drive)
{
struct bio bio;
struct bio_vec bio_vec;
struct page *page;
struct rb0_cbdata cbdata;
size_t size;
page = alloc_page(GFP_NOIO);
if (!page) {
process_fd_request();
return -ENOMEM;
}
size = bdev->bd_block_size;
if (!size)
size = 1024;
cbdata.drive = drive;
bio_init(&bio, &bio_vec, 1);
bio_set_dev(&bio, bdev);
bio_add_page(&bio, page, size, 0);
bio.bi_iter.bi_sector = 0;
bio.bi_flags |= (1 << BIO_QUIET);
bio.bi_private = &cbdata;
bio.bi_end_io = floppy_rb0_cb;
bio_set_op_attrs(&bio, REQ_OP_READ, 0);
init_completion(&cbdata.complete);
submit_bio(&bio);
process_fd_request();
wait_for_completion(&cbdata.complete);
__free_page(page);
return 0;
}
/* revalidate the floppy disk, i.e. trigger format autodetection by reading
* the bootblock (block 0). "Autodetection" is also needed to check whether
* there is a disk in the drive at all... Thus we also do it for fixed
* geometry formats */
static int floppy_revalidate(struct gendisk *disk)
{
int drive = (long)disk->private_data;
int cf;
int res = 0;
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
test_bit(drive, &fake_change) ||
drive_no_geom(drive)) {
if (WARN(atomic_read(&usage_count) == 0,
"VFS: revalidate called on non-open device.\n"))
return -EFAULT;
res = lock_fdc(drive);
if (res)
return res;
cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags));
if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) {
process_fd_request(); /*already done by another thread */
return 0;
}
UDRS->maxblock = 0;
UDRS->maxtrack = 0;
if (buffer_drive == drive)
buffer_track = -1;
clear_bit(drive, &fake_change);
clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
if (cf)
UDRS->generation++;
if (drive_no_geom(drive)) {
/* auto-sensing */
res = __floppy_read_block_0(opened_bdev[drive], drive);
} else {
if (cf)
poll_drive(false, FD_RAW_NEED_DISK);
process_fd_request();
}
}
set_capacity(disk, floppy_sizes[UDRS->fd_device]);
return res;
}
static const struct block_device_operations floppy_fops = {
.owner = THIS_MODULE,
.open = floppy_open,
.release = floppy_release,
.ioctl = fd_ioctl,
.getgeo = fd_getgeo,
.check_events = floppy_check_events,
.revalidate_disk = floppy_revalidate,
#ifdef CONFIG_COMPAT
.compat_ioctl = fd_compat_ioctl,
#endif
};
/*
* Floppy Driver initialization
* =============================
*/
/* Determine the floppy disk controller type */
/* This routine was written by David C. Niemi */
static char __init get_fdc_version(void)
{
int r;
output_byte(FD_DUMPREGS); /* 82072 and better know DUMPREGS */
if (FDCS->reset)
return FDC_NONE;
r = result();
if (r <= 0x00)
return FDC_NONE; /* No FDC present ??? */
if ((r == 1) && (reply_buffer[0] == 0x80)) {
pr_info("FDC %d is an 8272A\n", fdc);
return FDC_8272A; /* 8272a/765 don't know DUMPREGS */
}
if (r != 10) {
pr_info("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n",
fdc, r);
return FDC_UNKNOWN;
}
if (!fdc_configure()) {
pr_info("FDC %d is an 82072\n", fdc);
return FDC_82072; /* 82072 doesn't know CONFIGURE */
}
output_byte(FD_PERPENDICULAR);
if (need_more_output() == MORE_OUTPUT) {
output_byte(0);
} else {
pr_info("FDC %d is an 82072A\n", fdc);
return FDC_82072A; /* 82072A as found on Sparcs. */
}
output_byte(FD_UNLOCK);
r = result();
if ((r == 1) && (reply_buffer[0] == 0x80)) {
pr_info("FDC %d is a pre-1991 82077\n", fdc);
return FDC_82077_ORIG; /* Pre-1991 82077, doesn't know
* LOCK/UNLOCK */
}
if ((r != 1) || (reply_buffer[0] != 0x00)) {
pr_info("FDC %d init: UNLOCK: unexpected return of %d bytes.\n",
fdc, r);
return FDC_UNKNOWN;
}
output_byte(FD_PARTID);
r = result();
if (r != 1) {
pr_info("FDC %d init: PARTID: unexpected return of %d bytes.\n",
fdc, r);
return FDC_UNKNOWN;
}
if (reply_buffer[0] == 0x80) {
pr_info("FDC %d is a post-1991 82077\n", fdc);
return FDC_82077; /* Revised 82077AA passes all the tests */
}
switch (reply_buffer[0] >> 5) {
case 0x0:
/* Either a 82078-1 or a 82078SL running at 5Volt */
pr_info("FDC %d is an 82078.\n", fdc);
return FDC_82078;
case 0x1:
pr_info("FDC %d is a 44pin 82078\n", fdc);
return FDC_82078;
case 0x2:
pr_info("FDC %d is a S82078B\n", fdc);
return FDC_S82078B;
case 0x3:
pr_info("FDC %d is a National Semiconductor PC87306\n", fdc);
return FDC_87306;
default:
pr_info("FDC %d init: 82078 variant with unknown PARTID=%d.\n",
fdc, reply_buffer[0] >> 5);
return FDC_82078_UNKN;
}
} /* get_fdc_version */
/* lilo configuration */
static void __init floppy_set_flags(int *ints, int param, int param2)
{
int i;
for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {
if (param)
default_drive_params[i].params.flags |= param2;
else
default_drive_params[i].params.flags &= ~param2;
}
DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param);
}
static void __init daring(int *ints, int param, int param2)
{
int i;
for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {
if (param) {
default_drive_params[i].params.select_delay = 0;
default_drive_params[i].params.flags |=
FD_SILENT_DCL_CLEAR;
} else {
default_drive_params[i].params.select_delay =
2 * HZ / 100;
default_drive_params[i].params.flags &=
~FD_SILENT_DCL_CLEAR;
}
}
DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken");
}
static void __init set_cmos(int *ints, int dummy, int dummy2)
{
int current_drive = 0;
if (ints[0] != 2) {
DPRINT("wrong number of parameters for CMOS\n");
return;
}
current_drive = ints[1];
if (current_drive < 0 || current_drive >= 8) {
DPRINT("bad drive for set_cmos\n");
return;
}
#if N_FDC > 1
if (current_drive >= 4 && !FDC2)
FDC2 = 0x370;
#endif
DP->cmos = ints[2];
DPRINT("setting CMOS code to %d\n", ints[2]);
}
static struct param_table {
const char *name;
void (*fn) (int *ints, int param, int param2);
int *var;
int def_param;
int param2;
} config_params[] __initdata = {
{"allowed_drive_mask", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */
{"all_drives", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */
{"asus_pci", NULL, &allowed_drive_mask, 0x33, 0},
{"irq", NULL, &FLOPPY_IRQ, 6, 0},
{"dma", NULL, &FLOPPY_DMA, 2, 0},
{"daring", daring, NULL, 1, 0},
#if N_FDC > 1
{"two_fdc", NULL, &FDC2, 0x370, 0},
{"one_fdc", NULL, &FDC2, 0, 0},
#endif
{"thinkpad", floppy_set_flags, NULL, 1, FD_INVERTED_DCL},
{"broken_dcl", floppy_set_flags, NULL, 1, FD_BROKEN_DCL},
{"messages", floppy_set_flags, NULL, 1, FTD_MSG},
{"silent_dcl_clear", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR},
{"debug", floppy_set_flags, NULL, 1, FD_DEBUG},
{"nodma", NULL, &can_use_virtual_dma, 1, 0},
{"omnibook", NULL, &can_use_virtual_dma, 1, 0},
{"yesdma", NULL, &can_use_virtual_dma, 0, 0},
{"fifo_depth", NULL, &fifo_depth, 0xa, 0},
{"nofifo", NULL, &no_fifo, 0x20, 0},
{"usefifo", NULL, &no_fifo, 0, 0},
{"cmos", set_cmos, NULL, 0, 0},
{"slow", NULL, &slow_floppy, 1, 0},
{"unexpected_interrupts", NULL, &print_unex, 1, 0},
{"no_unexpected_interrupts", NULL, &print_unex, 0, 0},
{"L40SX", NULL, &print_unex, 0, 0}
EXTRA_FLOPPY_PARAMS
};
static int __init floppy_setup(char *str)
{
int i;
int param;
int ints[11];
str = get_options(str, ARRAY_SIZE(ints), ints);
if (str) {
for (i = 0; i < ARRAY_SIZE(config_params); i++) {
if (strcmp(str, config_params[i].name) == 0) {
if (ints[0])
param = ints[1];
else
param = config_params[i].def_param;
if (config_params[i].fn)
config_params[i].fn(ints, param,
config_params[i].
param2);
if (config_params[i].var) {
DPRINT("%s=%d\n", str, param);
*config_params[i].var = param;
}
return 1;
}
}
}
if (str) {
DPRINT("unknown floppy option [%s]\n", str);
DPRINT("allowed options are:");
for (i = 0; i < ARRAY_SIZE(config_params); i++)
pr_cont(" %s", config_params[i].name);
pr_cont("\n");
} else
DPRINT("botched floppy option\n");
DPRINT("Read Documentation/admin-guide/blockdev/floppy.rst\n");
return 0;
}
static int have_no_fdc = -ENODEV;
static ssize_t floppy_cmos_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *p = to_platform_device(dev);
int drive;
drive = p->id;
return sprintf(buf, "%X\n", UDP->cmos);
}
static DEVICE_ATTR(cmos, 0444, floppy_cmos_show, NULL);
static struct attribute *floppy_dev_attrs[] = {
&dev_attr_cmos.attr,
NULL
};
ATTRIBUTE_GROUPS(floppy_dev);
static void floppy_device_release(struct device *dev)
{
}
static int floppy_resume(struct device *dev)
{
int fdc;
for (fdc = 0; fdc < N_FDC; fdc++)
if (FDCS->address != -1)
user_reset_fdc(-1, FD_RESET_ALWAYS, false);
return 0;
}
static const struct dev_pm_ops floppy_pm_ops = {
.resume = floppy_resume,
.restore = floppy_resume,
};
static struct platform_driver floppy_driver = {
.driver = {
.name = "floppy",
.pm = &floppy_pm_ops,
},
};
static const struct blk_mq_ops floppy_mq_ops = {
.queue_rq = floppy_queue_rq,
};
static struct platform_device floppy_device[N_DRIVE];
static bool floppy_available(int drive)
{
if (!(allowed_drive_mask & (1 << drive)))
return false;
if (fdc_state[FDC(drive)].version == FDC_NONE)
return false;
return true;
}
static struct kobject *floppy_find(dev_t dev, int *part, void *data)
{
int drive = (*part & 3) | ((*part & 0x80) >> 5);
if (drive >= N_DRIVE || !floppy_available(drive))
return NULL;
if (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type))
return NULL;
*part = 0;
return get_disk_and_module(disks[drive]);
}
static int __init do_floppy_init(void)
{
int i, unit, drive, err;
set_debugt();
interruptjiffies = resultjiffies = jiffies;
#if defined(CONFIG_PPC)
if (check_legacy_ioport(FDC1))
return -ENODEV;
#endif
raw_cmd = NULL;
floppy_wq = alloc_ordered_workqueue("floppy", 0);
if (!floppy_wq)
return -ENOMEM;
for (drive = 0; drive < N_DRIVE; drive++) {
disks[drive] = alloc_disk(1);
if (!disks[drive]) {
err = -ENOMEM;
goto out_put_disk;
}
disks[drive]->queue = blk_mq_init_sq_queue(&tag_sets[drive],
&floppy_mq_ops, 2,
BLK_MQ_F_SHOULD_MERGE);
if (IS_ERR(disks[drive]->queue)) {
err = PTR_ERR(disks[drive]->queue);
disks[drive]->queue = NULL;
goto out_put_disk;
}
blk_queue_bounce_limit(disks[drive]->queue, BLK_BOUNCE_HIGH);
blk_queue_max_hw_sectors(disks[drive]->queue, 64);
disks[drive]->major = FLOPPY_MAJOR;
disks[drive]->first_minor = TOMINOR(drive);
disks[drive]->fops = &floppy_fops;
disks[drive]->events = DISK_EVENT_MEDIA_CHANGE;
sprintf(disks[drive]->disk_name, "fd%d", drive);
timer_setup(&motor_off_timer[drive], motor_off_callback, 0);
}
err = register_blkdev(FLOPPY_MAJOR, "fd");
if (err)
goto out_put_disk;
err = platform_driver_register(&floppy_driver);
if (err)
goto out_unreg_blkdev;
blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
floppy_find, NULL, NULL);
for (i = 0; i < 256; i++)
if (ITYPE(i))
floppy_sizes[i] = floppy_type[ITYPE(i)].size;
else
floppy_sizes[i] = MAX_DISK_SIZE << 1;
reschedule_timeout(MAXTIMEOUT, "floppy init");
config_types();
for (i = 0; i < N_FDC; i++) {
fdc = i;
memset(FDCS, 0, sizeof(*FDCS));
FDCS->dtr = -1;
FDCS->dor = 0x4;
#if defined(__sparc__) || defined(__mc68000__)
/*sparcs/sun3x don't have a DOR reset which we can fall back on to */
#ifdef __mc68000__
if (MACH_IS_SUN3X)
#endif
FDCS->version = FDC_82072A;
#endif
}
use_virtual_dma = can_use_virtual_dma & 1;
fdc_state[0].address = FDC1;
if (fdc_state[0].address == -1) {
cancel_delayed_work(&fd_timeout);
err = -ENODEV;
goto out_unreg_region;
}
#if N_FDC > 1
fdc_state[1].address = FDC2;
#endif
fdc = 0; /* reset fdc in case of unexpected interrupt */
err = floppy_grab_irq_and_dma();
if (err) {
cancel_delayed_work(&fd_timeout);
err = -EBUSY;
goto out_unreg_region;
}
/* initialise drive state */
for (drive = 0; drive < N_DRIVE; drive++) {
memset(UDRS, 0, sizeof(*UDRS));
memset(UDRWE, 0, sizeof(*UDRWE));
set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
set_bit(FD_VERIFY_BIT, &UDRS->flags);
UDRS->fd_device = -1;
floppy_track_buffer = NULL;
max_buffer_sectors = 0;
}
/*
* Small 10 msec delay to let through any interrupt that
* initialization might have triggered, to not
* confuse detection:
*/
msleep(10);
for (i = 0; i < N_FDC; i++) {
fdc = i;
FDCS->driver_version = FD_DRIVER_VERSION;
for (unit = 0; unit < 4; unit++)
FDCS->track[unit] = 0;
if (FDCS->address == -1)
continue;
FDCS->rawcmd = 2;
if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) {
/* free ioports reserved by floppy_grab_irq_and_dma() */
floppy_release_regions(fdc);
FDCS->address = -1;
FDCS->version = FDC_NONE;
continue;
}
/* Try to determine the floppy controller type */
FDCS->version = get_fdc_version();
if (FDCS->version == FDC_NONE) {
/* free ioports reserved by floppy_grab_irq_and_dma() */
floppy_release_regions(fdc);
FDCS->address = -1;
continue;
}
if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)
can_use_virtual_dma = 0;
have_no_fdc = 0;
/* Not all FDCs seem to be able to handle the version command
* properly, so force a reset for the standard FDC clones,
* to avoid interrupt garbage.
*/
user_reset_fdc(-1, FD_RESET_ALWAYS, false);
}
fdc = 0;
cancel_delayed_work(&fd_timeout);
current_drive = 0;
initialized = true;
if (have_no_fdc) {
DPRINT("no floppy controllers found\n");
err = have_no_fdc;
goto out_release_dma;
}
for (drive = 0; drive < N_DRIVE; drive++) {
if (!floppy_available(drive))
continue;
floppy_device[drive].name = floppy_device_name;
floppy_device[drive].id = drive;
floppy_device[drive].dev.release = floppy_device_release;
floppy_device[drive].dev.groups = floppy_dev_groups;
err = platform_device_register(&floppy_device[drive]);
if (err)
goto out_remove_drives;
/* to be cleaned up... */
disks[drive]->private_data = (void *)(long)drive;
disks[drive]->flags |= GENHD_FL_REMOVABLE;
device_add_disk(&floppy_device[drive].dev, disks[drive], NULL);
}
return 0;
out_remove_drives:
while (drive--) {
if (floppy_available(drive)) {
del_gendisk(disks[drive]);
platform_device_unregister(&floppy_device[drive]);
}
}
out_release_dma:
if (atomic_read(&usage_count))
floppy_release_irq_and_dma();
out_unreg_region:
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
platform_driver_unregister(&floppy_driver);
out_unreg_blkdev:
unregister_blkdev(FLOPPY_MAJOR, "fd");
out_put_disk:
destroy_workqueue(floppy_wq);
for (drive = 0; drive < N_DRIVE; drive++) {
if (!disks[drive])
break;
if (disks[drive]->queue) {
del_timer_sync(&motor_off_timer[drive]);
blk_cleanup_queue(disks[drive]->queue);
disks[drive]->queue = NULL;
blk_mq_free_tag_set(&tag_sets[drive]);
}
put_disk(disks[drive]);
}
return err;
}
#ifndef MODULE
static __init void floppy_async_init(void *data, async_cookie_t cookie)
{
do_floppy_init();
}
#endif
static int __init floppy_init(void)
{
#ifdef MODULE
return do_floppy_init();
#else
/* Don't hold up the bootup by the floppy initialization */
async_schedule(floppy_async_init, NULL);
return 0;
#endif
}
static const struct io_region {
int offset;
int size;
} io_regions[] = {
{ 2, 1 },
/* address + 3 is sometimes reserved by pnp bios for motherboard */
{ 4, 2 },
/* address + 6 is reserved, and may be taken by IDE.
* Unfortunately, Adaptec doesn't know this :-(, */
{ 7, 1 },
};
static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
{
while (p != io_regions) {
p--;
release_region(FDCS->address + p->offset, p->size);
}
}
#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
static int floppy_request_regions(int fdc)
{
const struct io_region *p;
for (p = io_regions; p < ARRAY_END(io_regions); p++) {
if (!request_region(FDCS->address + p->offset,
p->size, "floppy")) {
DPRINT("Floppy io-port 0x%04lx in use\n",
FDCS->address + p->offset);
floppy_release_allocated_regions(fdc, p);
return -EBUSY;
}
}
return 0;
}
static void floppy_release_regions(int fdc)
{
floppy_release_allocated_regions(fdc, ARRAY_END(io_regions));
}
static int floppy_grab_irq_and_dma(void)
{
if (atomic_inc_return(&usage_count) > 1)
return 0;
/*
* We might have scheduled a free_irq(), wait it to
* drain first:
*/
flush_workqueue(floppy_wq);
if (fd_request_irq()) {
DPRINT("Unable to grab IRQ%d for the floppy driver\n",
FLOPPY_IRQ);
atomic_dec(&usage_count);
return -1;
}
if (fd_request_dma()) {
DPRINT("Unable to grab DMA%d for the floppy driver\n",
FLOPPY_DMA);
if (can_use_virtual_dma & 2)
use_virtual_dma = can_use_virtual_dma = 1;
if (!(can_use_virtual_dma & 1)) {
fd_free_irq();
atomic_dec(&usage_count);
return -1;
}
}
for (fdc = 0; fdc < N_FDC; fdc++) {
if (FDCS->address != -1) {
if (floppy_request_regions(fdc))
goto cleanup;
}
}
for (fdc = 0; fdc < N_FDC; fdc++) {
if (FDCS->address != -1) {
reset_fdc_info(1);
fd_outb(FDCS->dor, FD_DOR);
}
}
fdc = 0;
set_dor(0, ~0, 8); /* avoid immediate interrupt */
for (fdc = 0; fdc < N_FDC; fdc++)
if (FDCS->address != -1)
fd_outb(FDCS->dor, FD_DOR);
/*
* The driver will try and free resources and relies on us
* to know if they were allocated or not.
*/
fdc = 0;
irqdma_allocated = 1;
return 0;
cleanup:
fd_free_irq();
fd_free_dma();
while (--fdc >= 0)
floppy_release_regions(fdc);
atomic_dec(&usage_count);
return -1;
}
static void floppy_release_irq_and_dma(void)
{
int old_fdc;
#ifndef __sparc__
int drive;
#endif
long tmpsize;
unsigned long tmpaddr;
if (!atomic_dec_and_test(&usage_count))
return;
if (irqdma_allocated) {
fd_disable_dma();
fd_free_dma();
fd_free_irq();
irqdma_allocated = 0;
}
set_dor(0, ~0, 8);
#if N_FDC > 1
set_dor(1, ~8, 0);
#endif
if (floppy_track_buffer && max_buffer_sectors) {
tmpsize = max_buffer_sectors * 1024;
tmpaddr = (unsigned long)floppy_track_buffer;
floppy_track_buffer = NULL;
max_buffer_sectors = 0;
buffer_min = buffer_max = -1;
fd_dma_mem_free(tmpaddr, tmpsize);
}
#ifndef __sparc__
for (drive = 0; drive < N_FDC * 4; drive++)
if (timer_pending(motor_off_timer + drive))
pr_info("motor off timer %d still active\n", drive);
#endif
if (delayed_work_pending(&fd_timeout))
pr_info("floppy timer still active:%s\n", timeout_message);
if (delayed_work_pending(&fd_timer))
pr_info("auxiliary floppy timer still active\n");
if (work_pending(&floppy_work))
pr_info("work still pending\n");
old_fdc = fdc;
for (fdc = 0; fdc < N_FDC; fdc++)
if (FDCS->address != -1)
floppy_release_regions(fdc);
fdc = old_fdc;
}
#ifdef MODULE
static char *floppy;
static void __init parse_floppy_cfg_string(char *cfg)
{
char *ptr;
while (*cfg) {
ptr = cfg;
while (*cfg && *cfg != ' ' && *cfg != '\t')
cfg++;
if (*cfg) {
*cfg = '\0';
cfg++;
}
if (*ptr)
floppy_setup(ptr);
}
}
static int __init floppy_module_init(void)
{
if (floppy)
parse_floppy_cfg_string(floppy);
return floppy_init();
}
module_init(floppy_module_init);
static void __exit floppy_module_exit(void)
{
int drive;
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
unregister_blkdev(FLOPPY_MAJOR, "fd");
platform_driver_unregister(&floppy_driver);
destroy_workqueue(floppy_wq);
for (drive = 0; drive < N_DRIVE; drive++) {
del_timer_sync(&motor_off_timer[drive]);
if (floppy_available(drive)) {
del_gendisk(disks[drive]);
platform_device_unregister(&floppy_device[drive]);
}
blk_cleanup_queue(disks[drive]->queue);
blk_mq_free_tag_set(&tag_sets[drive]);
/*
* These disks have not called add_disk(). Don't put down
* queue reference in put_disk().
*/
if (!(allowed_drive_mask & (1 << drive)) ||
fdc_state[FDC(drive)].version == FDC_NONE)
disks[drive]->queue = NULL;
put_disk(disks[drive]);
}
cancel_delayed_work_sync(&fd_timeout);
cancel_delayed_work_sync(&fd_timer);
if (atomic_read(&usage_count))
floppy_release_irq_and_dma();
/* eject disk, if any */
fd_eject(0);
}
module_exit(floppy_module_exit);
module_param(floppy, charp, 0);
module_param(FLOPPY_IRQ, int, 0);
module_param(FLOPPY_DMA, int, 0);
MODULE_AUTHOR("Alain L. Knaff");
MODULE_SUPPORTED_DEVICE("fd");
MODULE_LICENSE("GPL");
/* This doesn't actually get used other than for module information */
static const struct pnp_device_id floppy_pnpids[] = {
{"PNP0700", 0},
{}
};
MODULE_DEVICE_TABLE(pnp, floppy_pnpids);
#else
__setup("floppy=", floppy_setup);
module_init(floppy_init)
#endif
MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4689_0 |
crossvul-cpp_data_good_486_6 | /* -*- c-basic-offset: 8 -*-
rdesktop: A Remote Desktop Protocol client.
Protocol services - Multipoint Communications Service
Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008
Copyright 2005-2011 Peter Astrand <astrand@cendio.se> for Cendio AB
Copyright 2018 Henrik Andersson <hean01@cendio.com> 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"
uint16 g_mcs_userid;
extern VCHANNEL g_channels[];
extern unsigned int g_num_channels;
/* Output a DOMAIN_PARAMS structure (ASN.1 BER) */
static void
mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens, int max_pdusize)
{
ber_out_header(s, MCS_TAG_DOMAIN_PARAMS, 32);
ber_out_integer(s, max_channels);
ber_out_integer(s, max_users);
ber_out_integer(s, max_tokens);
ber_out_integer(s, 1); /* num_priorities */
ber_out_integer(s, 0); /* min_throughput */
ber_out_integer(s, 1); /* max_height */
ber_out_integer(s, max_pdusize);
ber_out_integer(s, 2); /* ver_protocol */
}
/* Parse a DOMAIN_PARAMS structure (ASN.1 BER) */
static RD_BOOL
mcs_parse_domain_params(STREAM s)
{
uint32 length;
struct stream packet = *s;
ber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);
if (!s_check_rem(s, length))
{
rdp_protocol_error("mcs_parse_domain_params(), consume domain params from stream would overrun", &packet);
}
in_uint8s(s, length);
return s_check(s);
}
/* Send an MCS_CONNECT_INITIAL message (ASN.1 BER) */
static void
mcs_send_connect_initial(STREAM mcs_data)
{
int datalen = mcs_data->end - mcs_data->data;
int length = 9 + 3 * 34 + 4 + datalen;
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_init(length + 5);
ber_out_header(s, MCS_CONNECT_INITIAL, length);
ber_out_header(s, BER_TAG_OCTET_STRING, 1); /* calling domain */
out_uint8(s, 1);
ber_out_header(s, BER_TAG_OCTET_STRING, 1); /* called domain */
out_uint8(s, 1);
ber_out_header(s, BER_TAG_BOOLEAN, 1);
out_uint8(s, 0xff); /* upward flag */
mcs_out_domain_params(s, 34, 2, 0, 0xffff); /* target params */
mcs_out_domain_params(s, 1, 1, 1, 0x420); /* min params */
mcs_out_domain_params(s, 0xffff, 0xfc17, 0xffff, 0xffff); /* max params */
ber_out_header(s, BER_TAG_OCTET_STRING, datalen);
out_uint8p(s, mcs_data->data, datalen);
s_mark_end(s);
iso_send(s);
}
/* Expect a MCS_CONNECT_RESPONSE message (ASN.1 BER) */
static RD_BOOL
mcs_recv_connect_response(STREAM mcs_data)
{
UNUSED(mcs_data);
uint8 result;
uint32 length;
STREAM s;
struct stream packet;
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
packet = *s;
ber_parse_header(s, MCS_CONNECT_RESPONSE, &length);
ber_parse_header(s, BER_TAG_RESULT, &length);
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result);
return False;
}
ber_parse_header(s, BER_TAG_INTEGER, &length);
in_uint8s(s, length); /* connect id */
if (!s_check_rem(s, length))
{
rdp_protocol_error("mcs_recv_connect_response(), consume connect id from stream would overrun", &packet);
}
mcs_parse_domain_params(s);
ber_parse_header(s, BER_TAG_OCTET_STRING, &length);
sec_process_mcs_data(s);
/*
if (length > mcs_data->size)
{
logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size);
length = mcs_data->size;
}
in_uint8a(s, mcs_data->data, length);
mcs_data->p = mcs_data->data;
mcs_data->end = mcs_data->data + length;
*/
return s_check_end(s);
}
/* Send an EDrq message (ASN.1 PER) */
static void
mcs_send_edrq(void)
{
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_init(5);
out_uint8(s, (MCS_EDRQ << 2));
out_uint16_be(s, 1); /* height */
out_uint16_be(s, 1); /* interval */
s_mark_end(s);
iso_send(s);
}
/* Send an AUrq message (ASN.1 PER) */
static void
mcs_send_aurq(void)
{
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_init(1);
out_uint8(s, (MCS_AURQ << 2));
s_mark_end(s);
iso_send(s);
}
/* Expect a AUcf message (ASN.1 PER) */
static RD_BOOL
mcs_recv_aucf(uint16 * mcs_userid)
{
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
uint8 opcode, result;
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
in_uint8(s, opcode);
if ((opcode >> 2) != MCS_AUCF)
{
logger(Protocol, Error, "mcs_recv_aucf(), expected opcode AUcf, got %d", opcode);
return False;
}
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_aucf(), expected result 0, got %d", result);
return False;
}
if (opcode & 2)
in_uint16_be(s, *mcs_userid);
return s_check_end(s);
}
/* Send a CJrq message (ASN.1 PER) */
static void
mcs_send_cjrq(uint16 chanid)
{
STREAM s;
logger(Protocol, Debug, "mcs_send_cjrq(), chanid=%d", chanid);
s = iso_init(5);
out_uint8(s, (MCS_CJRQ << 2));
out_uint16_be(s, g_mcs_userid);
out_uint16_be(s, chanid);
s_mark_end(s);
iso_send(s);
}
/* Expect a CJcf message (ASN.1 PER) */
static RD_BOOL
mcs_recv_cjcf(void)
{
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
uint8 opcode, result;
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
in_uint8(s, opcode);
if ((opcode >> 2) != MCS_CJCF)
{
logger(Protocol, Error, "mcs_recv_cjcf(), expected opcode CJcf, got %d", opcode);
return False;
}
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_cjcf(), expected result 0, got %d", result);
return False;
}
in_uint8s(s, 4); /* mcs_userid, req_chanid */
if (opcode & 2)
in_uint8s(s, 2); /* join_chanid */
return s_check_end(s);
}
/* Send MCS Disconnect provider ultimatum PDU */
void
mcs_send_dpu(unsigned short reason)
{
STREAM s, contents;
logger(Protocol, Debug, "mcs_send_dpu(), reason=%d", reason);
contents = malloc(sizeof(struct stream));
memset(contents, 0, sizeof(struct stream));
s_realloc(contents, 6);
s_reset(contents);
ber_out_integer(contents, reason); /* Reason */
ber_out_sequence(contents, NULL); /* SEQUENCE OF NonStandradParameters OPTIONAL */
s_mark_end(contents);
s = iso_init(8);
ber_out_sequence(s, contents);
s_free(contents);
s_mark_end(s);
iso_send(s);
}
/* Initialise an MCS transport data packet */
STREAM
mcs_init(int length)
{
STREAM s;
s = iso_init(length + 8);
s_push_layer(s, mcs_hdr, 8);
return s;
}
/* Send an MCS transport data packet to a specific channel */
void
mcs_send_to_channel(STREAM s, uint16 channel)
{
uint16 length;
s_pop_layer(s, mcs_hdr);
length = s->end - s->p - 8;
length |= 0x8000;
out_uint8(s, (MCS_SDRQ << 2));
out_uint16_be(s, g_mcs_userid);
out_uint16_be(s, channel);
out_uint8(s, 0x70); /* flags */
out_uint16_be(s, length);
iso_send(s);
}
/* Send an MCS transport data packet to the global channel */
void
mcs_send(STREAM s)
{
mcs_send_to_channel(s, MCS_GLOBAL_CHANNEL);
}
/* Receive an MCS transport data packet */
STREAM
mcs_recv(uint16 * channel, RD_BOOL * is_fastpath, uint8 * fastpath_hdr)
{
uint8 opcode, appid, length;
STREAM s;
s = iso_recv(is_fastpath, fastpath_hdr);
if (s == NULL)
return NULL;
if (*is_fastpath == True)
return s;
in_uint8(s, opcode);
appid = opcode >> 2;
if (appid != MCS_SDIN)
{
if (appid != MCS_DPUM)
{
logger(Protocol, Error, "mcs_recv(), expected data, got %d", opcode);
}
return NULL;
}
in_uint8s(s, 2); /* userid */
in_uint16_be(s, *channel);
in_uint8s(s, 1); /* flags */
in_uint8(s, length);
if (length & 0x80)
in_uint8s(s, 1); /* second byte of length */
return s;
}
RD_BOOL
mcs_connect_start(char *server, char *username, char *domain, char *password,
RD_BOOL reconnect, uint32 * selected_protocol)
{
logger(Protocol, Debug, "%s()", __func__);
return iso_connect(server, username, domain, password, reconnect, selected_protocol);
}
RD_BOOL
mcs_connect_finalize(STREAM mcs_data)
{
unsigned int i;
logger(Protocol, Debug, "%s()", __func__);
mcs_send_connect_initial(mcs_data);
if (!mcs_recv_connect_response(mcs_data))
goto error;
mcs_send_edrq();
mcs_send_aurq();
if (!mcs_recv_aucf(&g_mcs_userid))
goto error;
mcs_send_cjrq(g_mcs_userid + MCS_USERCHANNEL_BASE);
if (!mcs_recv_cjcf())
goto error;
mcs_send_cjrq(MCS_GLOBAL_CHANNEL);
if (!mcs_recv_cjcf())
goto error;
for (i = 0; i < g_num_channels; i++)
{
mcs_send_cjrq(g_channels[i].mcs_id);
if (!mcs_recv_cjcf())
goto error;
}
return True;
error:
iso_disconnect();
return False;
}
/* Disconnect from the MCS layer */
void
mcs_disconnect(int reason)
{
mcs_send_dpu(reason);
iso_disconnect();
}
/* reset the state of the mcs layer */
void
mcs_reset_state(void)
{
g_mcs_userid = 0;
iso_reset_state();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_486_6 |
crossvul-cpp_data_bad_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),
st->st_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/bad_4250_0 |
crossvul-cpp_data_good_1853_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;
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,"ImproperImageHeader");
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,"ImproperImageHeader");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
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);
else
{
if (sun_info.length > (height*bytes_per_line))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
(void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);
}
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)
{
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;
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/good_1853_0 |
crossvul-cpp_data_good_4019_2 | /* exif-mnote-data-olympus.c
*
* Copyright (c) 2002, 2003 Lutz Mueller <lutz@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*/
#include <config.h>
#include "exif-mnote-data-olympus.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <libexif/exif-utils.h>
#include <libexif/exif-data.h>
/* Uncomment this to fix a problem with Sanyo MakerNotes. It's probably best
* not to in most cases because it seems to only affect the thumbnail tag
* which is duplicated in IFD 1, and fixing the offset could actually cause
* problems with other software that expects the broken form.
*/
/*#define EXIF_OVERCOME_SANYO_OFFSET_BUG */
#define CHECKOVERFLOW(offset,datasize,structsize) (( offset >= datasize) || (structsize > datasize) || (offset > datasize - structsize ))
static enum OlympusVersion
exif_mnote_data_olympus_identify_variant (const unsigned char *buf,
unsigned int buf_size);
static void
exif_mnote_data_olympus_clear (ExifMnoteDataOlympus *n)
{
ExifMnoteData *d = (ExifMnoteData *) n;
unsigned int i;
if (!n) return;
if (n->entries) {
for (i = 0; i < n->count; i++)
if (n->entries[i].data) {
exif_mem_free (d->mem, n->entries[i].data);
n->entries[i].data = NULL;
}
exif_mem_free (d->mem, n->entries);
n->entries = NULL;
n->count = 0;
}
}
static void
exif_mnote_data_olympus_free (ExifMnoteData *n)
{
if (!n) return;
exif_mnote_data_olympus_clear ((ExifMnoteDataOlympus *) n);
}
static char *
exif_mnote_data_olympus_get_value (ExifMnoteData *d, unsigned int i, char *val, unsigned int maxlen)
{
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) d;
if (!d || !val) return NULL;
if (i > n->count -1) return NULL;
/*
exif_log (d->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Querying value for tag '%s'...",
mnote_olympus_tag_get_name (n->entries[i].tag));
*/
return mnote_olympus_entry_get_value (&n->entries[i], val, maxlen);
}
/**
* @brief save the MnoteData from ne to buf
*
* @param ne extract the data from this structure
* @param *buf write the mnoteData to this buffer (buffer will be allocated)
* @param buf_size the size of the buffer
*/
static void
exif_mnote_data_olympus_save (ExifMnoteData *ne,
unsigned char **buf, unsigned int *buf_size)
{
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) ne;
size_t i, o, s, doff, base = 0, o2 = 6 + 2;
size_t datao = 0;
unsigned char *t;
size_t ts;
if (!n || !buf || !buf_size) return;
/*
* Allocate enough memory for all entries and the number of entries.
*/
*buf_size = 6 + 2 + 2 + n->count * 12;
switch (n->version) {
case olympusV1:
case sanyoV1:
case epsonV1:
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataOlympus", *buf_size);
return;
}
/* Write the header and the number of entries. */
strcpy ((char *)*buf, n->version==sanyoV1?"SANYO":
(n->version==epsonV1?"EPSON":"OLYMP"));
exif_set_short (*buf + 6, n->order, (ExifShort) 1);
datao = n->offset;
break;
case olympusV2:
*buf_size += 8-6 + 4;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataOlympus", *buf_size);
return;
}
/* Write the header and the number of entries. */
strcpy ((char *)*buf, "OLYMPUS");
exif_set_short (*buf + 8, n->order, (ExifShort) (
(n->order == EXIF_BYTE_ORDER_INTEL) ?
('I' << 8) | 'I' :
('M' << 8) | 'M'));
exif_set_short (*buf + 10, n->order, (ExifShort) 3);
o2 += 4;
break;
case nikonV1:
base = MNOTE_NIKON1_TAG_BASE;
/* v1 has offsets based to main IFD, not makernote IFD */
datao += n->offset + 10;
/* subtract the size here, so the increment in the next case will not harm us */
*buf_size -= 8 + 2;
/* Fall through to nikonV2 handler */
case nikonV2:
/* Write out V0 files in V2 format */
case nikonV0:
*buf_size += 8 + 2;
*buf_size += 4; /* Next IFD pointer */
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataOlympus", *buf_size);
return;
}
/* Write the header and the number of entries. */
strcpy ((char *)*buf, "Nikon");
(*buf)[6] = n->version;
if (n->version != nikonV1) {
exif_set_short (*buf + 10, n->order, (ExifShort) (
(n->order == EXIF_BYTE_ORDER_INTEL) ?
('I' << 8) | 'I' :
('M' << 8) | 'M'));
exif_set_short (*buf + 12, n->order, (ExifShort) 0x2A);
exif_set_long (*buf + 14, n->order, (ExifShort) 8);
o2 += 2 + 8;
}
datao -= 10;
/* Reset next IFD pointer */
exif_set_long (*buf + o2 + 2 + n->count * 12, n->order, 0);
break;
default:
return;
}
exif_set_short (*buf + o2, n->order, (ExifShort) n->count);
o2 += 2;
/* Save each entry */
for (i = 0; i < n->count; i++) {
o = o2 + i * 12;
exif_set_short (*buf + o + 0, n->order,
(ExifShort) (n->entries[i].tag - base));
exif_set_short (*buf + o + 2, n->order,
(ExifShort) n->entries[i].format);
exif_set_long (*buf + o + 4, n->order,
n->entries[i].components);
o += 8;
s = exif_format_get_size (n->entries[i].format) *
n->entries[i].components;
if (s > 65536) {
/* Corrupt data: EXIF data size is limited to the
* maximum size of a JPEG segment (64 kb).
*/
continue;
}
if (s > 4) {
doff = *buf_size;
ts = *buf_size + s;
t = exif_mem_realloc (ne->mem, *buf,
sizeof (char) * ts);
if (!t) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataOlympus", ts);
return;
}
*buf = t;
*buf_size = ts;
exif_set_long (*buf + o, n->order, datao + doff);
} else
doff = o;
/* Write the data. */
if (n->entries[i].data) {
memcpy (*buf + doff, n->entries[i].data, s);
} else {
/* Most certainly damaged input file */
memset (*buf + doff, 0, s);
}
}
}
static void
exif_mnote_data_olympus_load (ExifMnoteData *en,
const unsigned char *buf, unsigned int buf_size)
{
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) en;
ExifShort c;
size_t i, tcount, o, o2, datao = 6, base = 0;
if (!n || !buf || !buf_size) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataOlympus", "Short MakerNote");
return;
}
o2 = 6 + n->offset; /* Start of interesting data */
if (CHECKOVERFLOW(o2,buf_size,10)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataOlympus", "Short MakerNote");
return;
}
/*
* Olympus headers start with "OLYMP" and need to have at least
* a size of 22 bytes (6 for 'OLYMP', 2 other bytes, 2 for the
* number of entries, and 12 for one entry.
*
* Sanyo format is identical and uses identical tags except that
* header starts with "SANYO".
*
* Epson format is identical and uses identical tags except that
* header starts with "EPSON".
*
* Nikon headers start with "Nikon" (6 bytes including '\0'),
* version number (1 or 2).
*
* Version 1 continues with 0, 1, 0, number_of_tags,
* or just with number_of_tags (models D1H, D1X...).
*
* Version 2 continues with an unknown byte (0 or 10),
* two unknown bytes (0), "MM" or "II", another byte 0 and
* lastly 0x2A.
*/
n->version = exif_mnote_data_olympus_identify_variant(buf+o2, buf_size-o2);
switch (n->version) {
case olympusV1:
case sanyoV1:
case epsonV1:
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Parsing Olympus/Sanyo/Epson maker note v1...");
/* The number of entries is at position 8. */
if (buf[o2 + 6] == 1)
n->order = EXIF_BYTE_ORDER_INTEL;
else if (buf[o2 + 6 + 1] == 1)
n->order = EXIF_BYTE_ORDER_MOTOROLA;
o2 += 8;
c = exif_get_short (buf + o2, n->order);
if ((!(c & 0xFF)) && (c > 0x500)) {
if (n->order == EXIF_BYTE_ORDER_INTEL) {
n->order = EXIF_BYTE_ORDER_MOTOROLA;
} else {
n->order = EXIF_BYTE_ORDER_INTEL;
}
}
break;
case olympusV2:
/* Olympus S760, S770 */
datao = o2;
o2 += 8;
if (CHECKOVERFLOW(o2,buf_size,4)) return;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Parsing Olympus maker note v2 (0x%02x, %02x, %02x, %02x)...",
buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3]);
if ((buf[o2] == 'I') && (buf[o2 + 1] == 'I'))
n->order = EXIF_BYTE_ORDER_INTEL;
else if ((buf[o2] == 'M') && (buf[o2 + 1] == 'M'))
n->order = EXIF_BYTE_ORDER_MOTOROLA;
/* The number of entries is at position 8+4. */
o2 += 4;
break;
case nikonV1:
o2 += 6;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Parsing Nikon maker note v1 (0x%02x, %02x, %02x, "
"%02x)...",
buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3]);
/* Skip version number */
o2 += 1;
/* Skip an unknown byte (00 or 0A). */
o2 += 1;
base = MNOTE_NIKON1_TAG_BASE;
/* Fix endianness, if needed */
c = exif_get_short (buf + o2, n->order);
if ((!(c & 0xFF)) && (c > 0x500)) {
if (n->order == EXIF_BYTE_ORDER_INTEL) {
n->order = EXIF_BYTE_ORDER_MOTOROLA;
} else {
n->order = EXIF_BYTE_ORDER_INTEL;
}
}
break;
case nikonV2:
o2 += 6;
if (CHECKOVERFLOW(o2,buf_size,12)) return;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Parsing Nikon maker note v2 (0x%02x, %02x, %02x, "
"%02x, %02x, %02x, %02x, %02x)...",
buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3],
buf[o2 + 4], buf[o2 + 5], buf[o2 + 6], buf[o2 + 7]);
/* Skip version number */
o2 += 1;
/* Skip an unknown byte (00 or 0A). */
o2 += 1;
/* Skip 2 unknown bytes (00 00). */
o2 += 2;
/*
* Byte order. From here the data offset
* gets calculated.
*/
datao = o2;
if (!strncmp ((char *)&buf[o2], "II", 2))
n->order = EXIF_BYTE_ORDER_INTEL;
else if (!strncmp ((char *)&buf[o2], "MM", 2))
n->order = EXIF_BYTE_ORDER_MOTOROLA;
else {
exif_log (en->log, EXIF_LOG_CODE_DEBUG,
"ExifMnoteDataOlympus", "Unknown "
"byte order '%c%c'", buf[o2],
buf[o2 + 1]);
return;
}
o2 += 2;
/* Skip 2 unknown bytes (00 2A). */
o2 += 2;
/* Go to where the number of entries is. */
o2 = datao + exif_get_long (buf + o2, n->order);
break;
case nikonV0:
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Parsing Nikon maker note v0 (0x%02x, %02x, %02x, "
"%02x, %02x, %02x, %02x, %02x)...",
buf[o2 + 0], buf[o2 + 1], buf[o2 + 2], buf[o2 + 3],
buf[o2 + 4], buf[o2 + 5], buf[o2 + 6], buf[o2 + 7]);
/* 00 1b is # of entries in Motorola order - the rest should also be in MM order */
n->order = EXIF_BYTE_ORDER_MOTOROLA;
break;
default:
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataOlympus",
"Unknown Olympus variant %i.", n->version);
return;
}
/* Sanity check the offset */
if (CHECKOVERFLOW(o2,buf_size,2)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteOlympus", "Short MakerNote");
return;
}
/* Read the number of tags */
c = exif_get_short (buf + o2, n->order);
o2 += 2;
/* Remove any old entries */
exif_mnote_data_olympus_clear (n);
/* Reserve enough space for all the possible MakerNote tags */
n->entries = exif_mem_alloc (en->mem, sizeof (MnoteOlympusEntry) * c);
if (!n->entries) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteOlympus", sizeof (MnoteOlympusEntry) * c);
return;
}
/* Parse all c entries, storing ones that are successfully parsed */
tcount = 0;
for (i = c, o = o2; i; --i, o += 12) {
size_t s;
if (CHECKOVERFLOW(o, buf_size, 12)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteOlympus", "Short MakerNote");
break;
}
n->entries[tcount].tag = exif_get_short (buf + o, n->order) + base;
n->entries[tcount].format = exif_get_short (buf + o + 2, n->order);
n->entries[tcount].components = exif_get_long (buf + o + 4, n->order);
n->entries[tcount].order = n->order;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteOlympus",
"Loading entry 0x%x ('%s')...", n->entries[tcount].tag,
mnote_olympus_tag_get_name (n->entries[tcount].tag));
/* exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteOlympus",
"0x%x %d %ld*(%d)",
n->entries[tcount].tag,
n->entries[tcount].format,
n->entries[tcount].components,
(int)exif_format_get_size(n->entries[tcount].format)); */
/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,
* we will check the buffer sizes closer later. */
if (exif_format_get_size (n->entries[tcount].format) &&
buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components
) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteOlympus", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);
continue;
}
/*
* Size? If bigger than 4 bytes, the actual data is not
* in the entry but somewhere else (offset).
*/
s = exif_format_get_size (n->entries[tcount].format) *
n->entries[tcount].components;
n->entries[tcount].size = s;
if (s) {
size_t dataofs = o + 8;
if (s > 4) {
/* The data in this case is merely a pointer */
dataofs = exif_get_long (buf + dataofs, n->order) + datao;
#ifdef EXIF_OVERCOME_SANYO_OFFSET_BUG
/* Some Sanyo models (e.g. VPC-C5, C40) suffer from a bug when
* writing the offset for the MNOTE_OLYMPUS_TAG_THUMBNAILIMAGE
* tag in its MakerNote. The offset is actually the absolute
* position in the file instead of the position within the IFD.
*/
if (dataofs > (buf_size - s) && n->version == sanyoV1) {
/* fix pointer */
dataofs -= datao + 6;
exif_log (en->log, EXIF_LOG_CODE_DEBUG,
"ExifMnoteOlympus",
"Inconsistent thumbnail tag offset; attempting to recover");
}
#endif
}
if (CHECKOVERFLOW(dataofs, buf_size, s)) {
exif_log (en->log, EXIF_LOG_CODE_DEBUG,
"ExifMnoteOlympus",
"Tag data past end of buffer (%u > %u)",
(unsigned)(dataofs + s), buf_size);
continue;
}
n->entries[tcount].data = exif_mem_alloc (en->mem, s);
if (!n->entries[tcount].data) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteOlympus", s);
continue;
}
memcpy (n->entries[tcount].data, buf + dataofs, s);
}
/* Tag was successfully parsed */
++tcount;
}
/* Store the count of successfully parsed tags */
n->count = tcount;
}
static unsigned int
exif_mnote_data_olympus_count (ExifMnoteData *n)
{
return n ? ((ExifMnoteDataOlympus *) n)->count : 0;
}
static unsigned int
exif_mnote_data_olympus_get_id (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataOlympus *note = (ExifMnoteDataOlympus *) d;
if (!note) return 0;
if (note->count <= n) return 0;
return note->entries[n].tag;
}
static const char *
exif_mnote_data_olympus_get_name (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_olympus_tag_get_name (n->entries[i].tag);
}
static const char *
exif_mnote_data_olympus_get_title (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_olympus_tag_get_title (n->entries[i].tag);
}
static const char *
exif_mnote_data_olympus_get_description (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_olympus_tag_get_description (n->entries[i].tag);
}
static void
exif_mnote_data_olympus_set_byte_order (ExifMnoteData *d, ExifByteOrder o)
{
ExifByteOrder o_orig;
ExifMnoteDataOlympus *n = (ExifMnoteDataOlympus *) d;
unsigned int i;
if (!n) return;
o_orig = n->order;
n->order = o;
for (i = 0; i < n->count; i++) {
if (n->entries[i].components && (n->entries[i].size/n->entries[i].components < exif_format_get_size (n->entries[i].format)))
continue;
n->entries[i].order = o;
exif_array_set_byte_order (n->entries[i].format, n->entries[i].data,
n->entries[i].components, o_orig, o);
}
}
static void
exif_mnote_data_olympus_set_offset (ExifMnoteData *n, unsigned int o)
{
if (n) ((ExifMnoteDataOlympus *) n)->offset = o;
}
static enum OlympusVersion
exif_mnote_data_olympus_identify_variant (const unsigned char *buf,
unsigned int buf_size)
{
/* Olympus, Nikon, Sanyo, Epson */
if (buf_size >= 8) {
/* Match the terminating NUL character, too */
if (!memcmp (buf, "OLYMPUS", 8))
return olympusV2;
else if (!memcmp (buf, "OLYMP", 6))
return olympusV1;
else if (!memcmp (buf, "SANYO", 6))
return sanyoV1;
else if (!memcmp (buf, "EPSON", 6))
return epsonV1;
else if (!memcmp (buf, "Nikon", 6)) {
switch (buf[6]) {
case 1: return nikonV1;
case 2: return nikonV2;
default: return 0; /* Unrecognized Nikon variant */
}
}
}
/* Another variant of Nikon */
if ((buf_size >= 2) && (buf[0] == 0x00) && (buf[1] == 0x1b)) {
return nikonV0;
}
return unrecognized;
}
int
exif_mnote_data_olympus_identify (const ExifData *ed, const ExifEntry *e)
{
int variant = exif_mnote_data_olympus_identify_variant(e->data, e->size);
if (variant == nikonV0) {
/* This variant needs some extra checking with the Make */
char value[5];
ExifEntry *em = exif_data_get_entry (ed, EXIF_TAG_MAKE);
variant = unrecognized;
if (em) {
const char *v = exif_entry_get_value (em, value, sizeof(value));
if (v && (!strncmp (v, "Nikon", sizeof(value)) ||
!strncmp (v, "NIKON", sizeof(value)) ))
/* When saved, this variant will be written out like the
* alternative nikonV2 form above instead
*/
variant = nikonV0;
}
}
return variant;
}
ExifMnoteData *
exif_mnote_data_olympus_new (ExifMem *mem)
{
ExifMnoteData *d;
if (!mem) return NULL;
d = exif_mem_alloc (mem, sizeof (ExifMnoteDataOlympus));
if (!d) return NULL;
exif_mnote_data_construct (d, mem);
/* Set up function pointers */
d->methods.free = exif_mnote_data_olympus_free;
d->methods.set_byte_order = exif_mnote_data_olympus_set_byte_order;
d->methods.set_offset = exif_mnote_data_olympus_set_offset;
d->methods.load = exif_mnote_data_olympus_load;
d->methods.save = exif_mnote_data_olympus_save;
d->methods.count = exif_mnote_data_olympus_count;
d->methods.get_id = exif_mnote_data_olympus_get_id;
d->methods.get_name = exif_mnote_data_olympus_get_name;
d->methods.get_title = exif_mnote_data_olympus_get_title;
d->methods.get_description = exif_mnote_data_olympus_get_description;
d->methods.get_value = exif_mnote_data_olympus_get_value;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4019_2 |
crossvul-cpp_data_bad_2924_0 | /* -*- linux-c -*-
GTCO digitizer USB driver
TO CHECK: Is pressure done right on report 5?
Copyright (C) 2006 GTCO CalComp
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of GTCO-CalComp not be used in advertising
or publicity pertaining to distribution of the software without specific,
written prior permission. GTCO-CalComp makes no representations about the
suitability of this software for any purpose. It is provided "as is"
without express or implied warranty.
GTCO-CALCOMP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL GTCO-CALCOMP BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTIONS, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
GTCO CalComp, Inc.
7125 Riverwood Drive
Columbia, MD 21046
Jeremy Roberson jroberson@gtcocalcomp.com
Scott Hill shill@gtcocalcomp.com
*/
/*#define DEBUG*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <linux/bitops.h>
#include <linux/usb/input.h>
/* Version with a Major number of 2 is for kernel inclusion only. */
#define GTCO_VERSION "2.00.0006"
/* MACROS */
#define VENDOR_ID_GTCO 0x078C
#define PID_400 0x400
#define PID_401 0x401
#define PID_1000 0x1000
#define PID_1001 0x1001
#define PID_1002 0x1002
/* Max size of a single report */
#define REPORT_MAX_SIZE 10
/* Bitmask whether pen is in range */
#define MASK_INRANGE 0x20
#define MASK_BUTTON 0x01F
#define PATHLENGTH 64
/* DATA STRUCTURES */
/* Device table */
static const struct usb_device_id gtco_usbid_table[] = {
{ USB_DEVICE(VENDOR_ID_GTCO, PID_400) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_401) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1000) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1001) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1002) },
{ }
};
MODULE_DEVICE_TABLE (usb, gtco_usbid_table);
/* Structure to hold all of our device specific stuff */
struct gtco {
struct input_dev *inputdevice; /* input device struct pointer */
struct usb_interface *intf; /* the usb interface for this device */
struct urb *urbinfo; /* urb for incoming reports */
dma_addr_t buf_dma; /* dma addr of the data buffer*/
unsigned char * buffer; /* databuffer for reports */
char usbpath[PATHLENGTH];
int openCount;
/* Information pulled from Report Descriptor */
u32 usage;
u32 min_X;
u32 max_X;
u32 min_Y;
u32 max_Y;
s8 mintilt_X;
s8 maxtilt_X;
s8 mintilt_Y;
s8 maxtilt_Y;
u32 maxpressure;
u32 minpressure;
};
/* Code for parsing the HID REPORT DESCRIPTOR */
/* From HID1.11 spec */
struct hid_descriptor
{
struct usb_descriptor_header header;
__le16 bcdHID;
u8 bCountryCode;
u8 bNumDescriptors;
u8 bDescriptorType;
__le16 wDescriptorLength;
} __attribute__ ((packed));
#define HID_DESCRIPTOR_SIZE 9
#define HID_DEVICE_TYPE 33
#define REPORT_DEVICE_TYPE 34
#define PREF_TAG(x) ((x)>>4)
#define PREF_TYPE(x) ((x>>2)&0x03)
#define PREF_SIZE(x) ((x)&0x03)
#define TYPE_MAIN 0
#define TYPE_GLOBAL 1
#define TYPE_LOCAL 2
#define TYPE_RESERVED 3
#define TAG_MAIN_INPUT 0x8
#define TAG_MAIN_OUTPUT 0x9
#define TAG_MAIN_FEATURE 0xB
#define TAG_MAIN_COL_START 0xA
#define TAG_MAIN_COL_END 0xC
#define TAG_GLOB_USAGE 0
#define TAG_GLOB_LOG_MIN 1
#define TAG_GLOB_LOG_MAX 2
#define TAG_GLOB_PHYS_MIN 3
#define TAG_GLOB_PHYS_MAX 4
#define TAG_GLOB_UNIT_EXP 5
#define TAG_GLOB_UNIT 6
#define TAG_GLOB_REPORT_SZ 7
#define TAG_GLOB_REPORT_ID 8
#define TAG_GLOB_REPORT_CNT 9
#define TAG_GLOB_PUSH 10
#define TAG_GLOB_POP 11
#define TAG_GLOB_MAX 12
#define DIGITIZER_USAGE_TIP_PRESSURE 0x30
#define DIGITIZER_USAGE_TILT_X 0x3D
#define DIGITIZER_USAGE_TILT_Y 0x3E
/*
* This is an abbreviated parser for the HID Report Descriptor. We
* know what devices we are talking to, so this is by no means meant
* to be generic. We can make some safe assumptions:
*
* - We know there are no LONG tags, all short
* - We know that we have no MAIN Feature and MAIN Output items
* - We know what the IRQ reports are supposed to look like.
*
* The main purpose of this is to use the HID report desc to figure
* out the mins and maxs of the fields in the IRQ reports. The IRQ
* reports for 400/401 change slightly if the max X is bigger than 64K.
*
*/
static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
struct device *ddev = &device->intf->dev;
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dev_dbg(ddev, "======>>>>>>PARSE<<<<<<======\n");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i];
/* Skip over prefix */
i++;
/* Determine data size and save the data in the proper variable */
size = PREF_SIZE(prefix);
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 3:
size = 4;
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dev_dbg(ddev, "::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits\n",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dev_dbg(ddev, "GER: X Usage: 0x%x\n", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dev_dbg(ddev, "GER: Y Usage: 0x%x\n", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dev_dbg(ddev, "======>>>>>> Physical\n");
strcpy(globtype, "Physical");
} else
dev_dbg(ddev, "======>>>>>>\n");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dev_dbg(ddev, "<<<<<<======\n");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dev_dbg(ddev, "%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d\n",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data);
break;
case 2:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data16);
break;
case 4:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
}
/* INPUT DRIVER Routines */
/*
* Called when opening the input device. This will submit the URB to
* the usb system so we start getting reports
*/
static int gtco_input_open(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
device->urbinfo->dev = interface_to_usbdev(device->intf);
if (usb_submit_urb(device->urbinfo, GFP_KERNEL))
return -EIO;
return 0;
}
/*
* Called when closing the input device. This will unlink the URB
*/
static void gtco_input_close(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
usb_kill_urb(device->urbinfo);
}
/*
* Setup input device capabilities. Tell the input system what this
* device is capable of generating.
*
* This information is based on what is read from the HID report and
* placed in the struct gtco structure
*
*/
static void gtco_setup_caps(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
/* Which events */
inputdev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) |
BIT_MASK(EV_MSC);
/* Misc event menu block */
inputdev->mscbit[0] = BIT_MASK(MSC_SCAN) | BIT_MASK(MSC_SERIAL) |
BIT_MASK(MSC_RAW);
/* Absolute values based on HID report info */
input_set_abs_params(inputdev, ABS_X, device->min_X, device->max_X,
0, 0);
input_set_abs_params(inputdev, ABS_Y, device->min_Y, device->max_Y,
0, 0);
/* Proximity */
input_set_abs_params(inputdev, ABS_DISTANCE, 0, 1, 0, 0);
/* Tilt & pressure */
input_set_abs_params(inputdev, ABS_TILT_X, device->mintilt_X,
device->maxtilt_X, 0, 0);
input_set_abs_params(inputdev, ABS_TILT_Y, device->mintilt_Y,
device->maxtilt_Y, 0, 0);
input_set_abs_params(inputdev, ABS_PRESSURE, device->minpressure,
device->maxpressure, 0, 0);
/* Transducer */
input_set_abs_params(inputdev, ABS_MISC, 0, 0xFF, 0, 0);
}
/* USB Routines */
/*
* URB callback routine. Called when we get IRQ reports from the
* digitizer.
*
* This bridges the USB and input device worlds. It generates events
* on the input device based on the USB reports.
*/
static void gtco_urb_callback(struct urb *urbinfo)
{
struct gtco *device = urbinfo->context;
struct input_dev *inputdev;
int rc;
u32 val = 0;
char le_buffer[2];
inputdev = device->inputdevice;
/* Was callback OK? */
if (urbinfo->status == -ECONNRESET ||
urbinfo->status == -ENOENT ||
urbinfo->status == -ESHUTDOWN) {
/* Shutdown is occurring. Return and don't queue up any more */
return;
}
if (urbinfo->status != 0) {
/*
* Some unknown error. Hopefully temporary. Just go and
* requeue an URB
*/
goto resubmit;
}
/*
* Good URB, now process
*/
/* PID dependent when we interpret the report */
if (inputdev->id.product == PID_1000 ||
inputdev->id.product == PID_1001 ||
inputdev->id.product == PID_1002) {
/*
* Switch on the report ID
* Conveniently, the reports have more information, the higher
* the report number. We can just fall through the case
* statements if we start with the highest number report
*/
switch (device->buffer[0]) {
case 5:
/* Pressure is 9 bits */
val = ((u16)(device->buffer[8]) << 1);
val |= (u16)(device->buffer[7] >> 7);
input_report_abs(inputdev, ABS_PRESSURE,
device->buffer[8]);
/* Mask out the Y tilt value used for pressure */
device->buffer[7] = (u8)((device->buffer[7]) & 0x7F);
/* Fall thru */
case 4:
/* Tilt */
input_report_abs(inputdev, ABS_TILT_X,
sign_extend32(device->buffer[6], 6));
input_report_abs(inputdev, ABS_TILT_Y,
sign_extend32(device->buffer[7], 6));
/* Fall thru */
case 2:
case 3:
/* Convert buttons, only 5 bits possible */
val = (device->buffer[5]) & MASK_BUTTON;
/* We don't apply any meaning to the bitmask,
just report */
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
/* Fall thru */
case 1:
/* All reports have X and Y coords in the same place */
val = get_unaligned_le16(&device->buffer[1]);
input_report_abs(inputdev, ABS_X, val);
val = get_unaligned_le16(&device->buffer[3]);
input_report_abs(inputdev, ABS_Y, val);
/* Ditto for proximity bit */
val = device->buffer[5] & MASK_INRANGE ? 1 : 0;
input_report_abs(inputdev, ABS_DISTANCE, val);
/* Report 1 is an exception to how we handle buttons */
/* Buttons are an index, not a bitmask */
if (device->buffer[0] == 1) {
/*
* Convert buttons, 5 bit index
* Report value of index set as one,
* the rest as 0
*/
val = device->buffer[5] & MASK_BUTTON;
dev_dbg(&device->intf->dev,
"======>>>>>>REPORT 1: val 0x%X(%d)\n",
val, val);
/*
* We don't apply any meaning to the button
* index, just report it
*/
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
}
break;
case 7:
/* Menu blocks */
input_event(inputdev, EV_MSC, MSC_SCAN,
device->buffer[1]);
break;
}
}
/* Other pid class */
if (inputdev->id.product == PID_400 ||
inputdev->id.product == PID_401) {
/* Report 2 */
if (device->buffer[0] == 2) {
/* Menu blocks */
input_event(inputdev, EV_MSC, MSC_SCAN, device->buffer[1]);
}
/* Report 1 */
if (device->buffer[0] == 1) {
char buttonbyte;
/* IF X max > 64K, we still a bit from the y report */
if (device->max_X > 0x10000) {
val = (u16)(((u16)(device->buffer[2] << 8)) | (u8)device->buffer[1]);
val |= (u32)(((u8)device->buffer[3] & 0x1) << 16);
input_report_abs(inputdev, ABS_X, val);
le_buffer[0] = (u8)((u8)(device->buffer[3]) >> 1);
le_buffer[0] |= (u8)((device->buffer[3] & 0x1) << 7);
le_buffer[1] = (u8)(device->buffer[4] >> 1);
le_buffer[1] |= (u8)((device->buffer[5] & 0x1) << 7);
val = get_unaligned_le16(le_buffer);
input_report_abs(inputdev, ABS_Y, val);
/*
* Shift the button byte right by one to
* make it look like the standard report
*/
buttonbyte = device->buffer[5] >> 1;
} else {
val = get_unaligned_le16(&device->buffer[1]);
input_report_abs(inputdev, ABS_X, val);
val = get_unaligned_le16(&device->buffer[3]);
input_report_abs(inputdev, ABS_Y, val);
buttonbyte = device->buffer[5];
}
/* BUTTONS and PROXIMITY */
val = buttonbyte & MASK_INRANGE ? 1 : 0;
input_report_abs(inputdev, ABS_DISTANCE, val);
/* Convert buttons, only 4 bits possible */
val = buttonbyte & 0x0F;
#ifdef USE_BUTTONS
for (i = 0; i < 5; i++)
input_report_key(inputdev, BTN_DIGI + i, val & (1 << i));
#else
/* We don't apply any meaning to the bitmask, just report */
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
#endif
/* TRANSDUCER */
input_report_abs(inputdev, ABS_MISC, device->buffer[6]);
}
}
/* Everybody gets report ID's */
input_event(inputdev, EV_MSC, MSC_RAW, device->buffer[0]);
/* Sync it up */
input_sync(inputdev);
resubmit:
rc = usb_submit_urb(urbinfo, GFP_ATOMIC);
if (rc != 0)
dev_err(&device->intf->dev,
"usb_submit_urb failed rc=0x%x\n", rc);
}
/*
* The probe routine. This is called when the kernel find the matching USB
* vendor/product. We do the following:
*
* - Allocate mem for a local structure to manage the device
* - Request a HID Report Descriptor from the device and parse it to
* find out the device parameters
* - Create an input device and assign it attributes
* - Allocate an URB so the device can talk to us when the input
* queue is open
*/
static int gtco_probe(struct usb_interface *usbinterface,
const struct usb_device_id *id)
{
struct gtco *gtco;
struct input_dev *input_dev;
struct hid_descriptor *hid_desc;
char *report;
int result = 0, retry;
int error;
struct usb_endpoint_descriptor *endpoint;
struct usb_device *udev = interface_to_usbdev(usbinterface);
/* Allocate memory for device structure */
gtco = kzalloc(sizeof(struct gtco), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gtco || !input_dev) {
dev_err(&usbinterface->dev, "No more memory\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Set pointer to the input device */
gtco->inputdevice = input_dev;
/* Save interface information */
gtco->intf = usbinterface;
/* Allocate some data for incoming reports */
gtco->buffer = usb_alloc_coherent(udev, REPORT_MAX_SIZE,
GFP_KERNEL, >co->buf_dma);
if (!gtco->buffer) {
dev_err(&usbinterface->dev, "No more memory for us buffers\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Allocate URB for reports */
gtco->urbinfo = usb_alloc_urb(0, GFP_KERNEL);
if (!gtco->urbinfo) {
dev_err(&usbinterface->dev, "Failed to allocate URB\n");
error = -ENOMEM;
goto err_free_buf;
}
/* Sanity check that a device has an endpoint */
if (usbinterface->altsetting[0].desc.bNumEndpoints < 1) {
dev_err(&usbinterface->dev,
"Invalid number of endpoints\n");
error = -EINVAL;
goto err_free_urb;
}
/*
* The endpoint is always altsetting 0, we know this since we know
* this device only has one interrupt endpoint
*/
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
/* Some debug */
dev_dbg(&usbinterface->dev, "gtco # interfaces: %d\n", usbinterface->num_altsetting);
dev_dbg(&usbinterface->dev, "num endpoints: %d\n", usbinterface->cur_altsetting->desc.bNumEndpoints);
dev_dbg(&usbinterface->dev, "interface class: %d\n", usbinterface->cur_altsetting->desc.bInterfaceClass);
dev_dbg(&usbinterface->dev, "endpoint: attribute:0x%x type:0x%x\n", endpoint->bmAttributes, endpoint->bDescriptorType);
if (usb_endpoint_xfer_int(endpoint))
dev_dbg(&usbinterface->dev, "endpoint: we have interrupt endpoint\n");
dev_dbg(&usbinterface->dev, "endpoint extra len:%d\n", usbinterface->altsetting[0].extralen);
/*
* Find the HID descriptor so we can find out the size of the
* HID report descriptor
*/
if (usb_get_extra_descriptor(usbinterface->cur_altsetting,
HID_DEVICE_TYPE, &hid_desc) != 0) {
dev_err(&usbinterface->dev,
"Can't retrieve exta USB descriptor to get hid report descriptor length\n");
error = -EIO;
goto err_free_urb;
}
dev_dbg(&usbinterface->dev,
"Extra descriptor success: type:%d len:%d\n",
hid_desc->bDescriptorType, hid_desc->wDescriptorLength);
report = kzalloc(le16_to_cpu(hid_desc->wDescriptorLength), GFP_KERNEL);
if (!report) {
dev_err(&usbinterface->dev, "No more memory for report\n");
error = -ENOMEM;
goto err_free_urb;
}
/* Couple of tries to get reply */
for (retry = 0; retry < 3; retry++) {
result = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
REPORT_DEVICE_TYPE << 8,
0, /* interface */
report,
le16_to_cpu(hid_desc->wDescriptorLength),
5000); /* 5 secs */
dev_dbg(&usbinterface->dev, "usb_control_msg result: %d\n", result);
if (result == le16_to_cpu(hid_desc->wDescriptorLength)) {
parse_hid_report_descriptor(gtco, report, result);
break;
}
}
kfree(report);
/* If we didn't get the report, fail */
if (result != le16_to_cpu(hid_desc->wDescriptorLength)) {
dev_err(&usbinterface->dev,
"Failed to get HID Report Descriptor of size: %d\n",
hid_desc->wDescriptorLength);
error = -EIO;
goto err_free_urb;
}
/* Create a device file node */
usb_make_path(udev, gtco->usbpath, sizeof(gtco->usbpath));
strlcat(gtco->usbpath, "/input0", sizeof(gtco->usbpath));
/* Set Input device functions */
input_dev->open = gtco_input_open;
input_dev->close = gtco_input_close;
/* Set input device information */
input_dev->name = "GTCO_CalComp";
input_dev->phys = gtco->usbpath;
input_set_drvdata(input_dev, gtco);
/* Now set up all the input device capabilities */
gtco_setup_caps(input_dev);
/* Set input device required ID information */
usb_to_input_id(udev, &input_dev->id);
input_dev->dev.parent = &usbinterface->dev;
/* Setup the URB, it will be posted later on open of input device */
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
usb_fill_int_urb(gtco->urbinfo,
udev,
usb_rcvintpipe(udev,
endpoint->bEndpointAddress),
gtco->buffer,
REPORT_MAX_SIZE,
gtco_urb_callback,
gtco,
endpoint->bInterval);
gtco->urbinfo->transfer_dma = gtco->buf_dma;
gtco->urbinfo->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Save gtco pointer in USB interface gtco */
usb_set_intfdata(usbinterface, gtco);
/* All done, now register the input device */
error = input_register_device(input_dev);
if (error)
goto err_free_urb;
return 0;
err_free_urb:
usb_free_urb(gtco->urbinfo);
err_free_buf:
usb_free_coherent(udev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
err_free_devs:
input_free_device(input_dev);
kfree(gtco);
return error;
}
/*
* This function is a standard USB function called when the USB device
* is disconnected. We will get rid of the URV, de-register the input
* device, and free up allocated memory
*/
static void gtco_disconnect(struct usb_interface *interface)
{
/* Grab private device ptr */
struct gtco *gtco = usb_get_intfdata(interface);
struct usb_device *udev = interface_to_usbdev(interface);
/* Now reverse all the registration stuff */
if (gtco) {
input_unregister_device(gtco->inputdevice);
usb_kill_urb(gtco->urbinfo);
usb_free_urb(gtco->urbinfo);
usb_free_coherent(udev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
kfree(gtco);
}
dev_info(&interface->dev, "gtco driver disconnected\n");
}
/* STANDARD MODULE LOAD ROUTINES */
static struct usb_driver gtco_driverinfo_table = {
.name = "gtco",
.id_table = gtco_usbid_table,
.probe = gtco_probe,
.disconnect = gtco_disconnect,
};
module_usb_driver(gtco_driverinfo_table);
MODULE_DESCRIPTION("GTCO digitizer USB driver");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2924_0 |
crossvul-cpp_data_bad_467_0 | /*
* MXF demuxer.
* Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* References
* SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
* SMPTE 377M MXF File Format Specifications
* SMPTE 378M Operational Pattern 1a
* SMPTE 379M MXF Generic Container
* SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
* SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container
* SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container
*
* Principle
* Search for Track numbers which will identify essence element KLV packets.
* Search for SourcePackage which define tracks which contains Track numbers.
* Material Package contains tracks with reference to SourcePackage tracks.
* Search for Descriptors (Picture, Sound) which contains codec info and parameters.
* Assign Descriptors to correct Tracks.
*
* Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext.
* Metadata parsing resolves Strong References to objects.
*
* Simple demuxer, only OP1A supported and some files might not work at all.
* Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1
*/
#include <inttypes.h>
#include "libavutil/aes.h"
#include "libavutil/avassert.h"
#include "libavutil/mathematics.h"
#include "libavcodec/bytestream.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/parseutils.h"
#include "libavutil/timecode.h"
#include "avformat.h"
#include "internal.h"
#include "mxf.h"
#define MXF_MAX_CHUNK_SIZE (32 << 20)
typedef enum {
Header,
BodyPartition,
Footer
} MXFPartitionType;
typedef enum {
OP1a = 1,
OP1b,
OP1c,
OP2a,
OP2b,
OP2c,
OP3a,
OP3b,
OP3c,
OPAtom,
OPSONYOpt, /* FATE sample, violates the spec in places */
} MXFOP;
typedef enum {
UnknownWrapped = 0,
FrameWrapped,
ClipWrapped,
} MXFWrappingScheme;
typedef struct MXFPartition {
int closed;
int complete;
MXFPartitionType type;
uint64_t previous_partition;
int index_sid;
int body_sid;
int64_t this_partition;
int64_t essence_offset; ///< absolute offset of essence
int64_t essence_length;
int32_t kag_size;
int64_t header_byte_count;
int64_t index_byte_count;
int pack_length;
int64_t pack_ofs; ///< absolute offset of pack in file, including run-in
int64_t body_offset;
KLVPacket first_essence_klv;
} MXFPartition;
typedef struct MXFCryptoContext {
UID uid;
enum MXFMetadataSetType type;
UID source_container_ul;
} MXFCryptoContext;
typedef struct MXFStructuralComponent {
UID uid;
enum MXFMetadataSetType type;
UID source_package_ul;
UID source_package_uid;
UID data_definition_ul;
int64_t duration;
int64_t start_position;
int source_track_id;
} MXFStructuralComponent;
typedef struct MXFSequence {
UID uid;
enum MXFMetadataSetType type;
UID data_definition_ul;
UID *structural_components_refs;
int structural_components_count;
int64_t duration;
uint8_t origin;
} MXFSequence;
typedef struct MXFTrack {
UID uid;
enum MXFMetadataSetType type;
int drop_frame;
int start_frame;
struct AVRational rate;
AVTimecode tc;
} MXFTimecodeComponent;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
UID input_segment_ref;
} MXFPulldownComponent;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
UID *structural_components_refs;
int structural_components_count;
int64_t duration;
} MXFEssenceGroup;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
char *name;
char *value;
} MXFTaggedValue;
typedef struct {
UID uid;
enum MXFMetadataSetType type;
MXFSequence *sequence; /* mandatory, and only one */
UID sequence_ref;
int track_id;
char *name;
uint8_t track_number[4];
AVRational edit_rate;
int intra_only;
uint64_t sample_count;
int64_t original_duration; /* st->duration in SampleRate/EditRate units */
int index_sid;
int body_sid;
MXFWrappingScheme wrapping;
int edit_units_per_packet; /* how many edit units to read at a time (PCM, ClipWrapped) */
} MXFTrack;
typedef struct MXFDescriptor {
UID uid;
enum MXFMetadataSetType type;
UID essence_container_ul;
UID essence_codec_ul;
UID codec_ul;
AVRational sample_rate;
AVRational aspect_ratio;
int width;
int height; /* Field height, not frame height */
int frame_layout; /* See MXFFrameLayout enum */
int video_line_map[2];
#define MXF_FIELD_DOMINANCE_DEFAULT 0
#define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */
#define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */
int field_dominance;
int channels;
int bits_per_sample;
int64_t duration; /* ContainerDuration optional property */
unsigned int component_depth;
unsigned int horiz_subsampling;
unsigned int vert_subsampling;
UID *sub_descriptors_refs;
int sub_descriptors_count;
int linked_track_id;
uint8_t *extradata;
int extradata_size;
enum AVPixelFormat pix_fmt;
} MXFDescriptor;
typedef struct MXFIndexTableSegment {
UID uid;
enum MXFMetadataSetType type;
int edit_unit_byte_count;
int index_sid;
int body_sid;
AVRational index_edit_rate;
uint64_t index_start_position;
uint64_t index_duration;
int8_t *temporal_offset_entries;
int *flag_entries;
uint64_t *stream_offset_entries;
int nb_index_entries;
} MXFIndexTableSegment;
typedef struct MXFPackage {
UID uid;
enum MXFMetadataSetType type;
UID package_uid;
UID package_ul;
UID *tracks_refs;
int tracks_count;
MXFDescriptor *descriptor; /* only one */
UID descriptor_ref;
char *name;
UID *comment_refs;
int comment_count;
} MXFPackage;
typedef struct MXFEssenceContainerData {
UID uid;
enum MXFMetadataSetType type;
UID package_uid;
UID package_ul;
int index_sid;
int body_sid;
} MXFEssenceContainerData;
typedef struct MXFMetadataSet {
UID uid;
enum MXFMetadataSetType type;
} MXFMetadataSet;
/* decoded index table */
typedef struct MXFIndexTable {
int index_sid;
int body_sid;
int nb_ptses; /* number of PTSes or total duration of index */
int64_t first_dts; /* DTS = EditUnit + first_dts */
int64_t *ptses; /* maps EditUnit -> PTS */
int nb_segments;
MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */
AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */
int8_t *offsets; /* temporal offsets for display order to stored order conversion */
} MXFIndexTable;
typedef struct MXFContext {
MXFPartition *partitions;
unsigned partitions_count;
MXFOP op;
UID *packages_refs;
int packages_count;
UID *essence_container_data_refs;
int essence_container_data_count;
MXFMetadataSet **metadata_sets;
int metadata_sets_count;
AVFormatContext *fc;
struct AVAES *aesc;
uint8_t *local_tags;
int local_tags_count;
uint64_t footer_partition;
KLVPacket current_klv_data;
int run_in;
MXFPartition *current_partition;
int parsing_backward;
int64_t last_forward_tell;
int last_forward_partition;
int nb_index_tables;
MXFIndexTable *index_tables;
} MXFContext;
/* NOTE: klv_offset is not set (-1) for local keys */
typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset);
typedef struct MXFMetadataReadTableEntry {
const UID key;
MXFMetadataReadFunc *read;
int ctx_size;
enum MXFMetadataSetType type;
} MXFMetadataReadTableEntry;
static int mxf_read_close(AVFormatContext *s);
/* partial keys to match */
static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 };
static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 };
static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 };
static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 };
static const uint8_t mxf_system_item_key_cp[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 };
static const uint8_t mxf_system_item_key_gc[] = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x03,0x01,0x14 };
static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 };
/* complete keys to match */
static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 };
static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 };
static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 };
static const uint8_t mxf_random_index_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 };
static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf };
static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 };
static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
static const uint8_t mxf_indirect_value_utf16be[] = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
#define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y)))
static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx)
{
MXFIndexTableSegment *seg;
switch ((*ctx)->type) {
case Descriptor:
av_freep(&((MXFDescriptor *)*ctx)->extradata);
break;
case MultipleDescriptor:
av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs);
break;
case Sequence:
av_freep(&((MXFSequence *)*ctx)->structural_components_refs);
break;
case EssenceGroup:
av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs);
break;
case SourcePackage:
case MaterialPackage:
av_freep(&((MXFPackage *)*ctx)->tracks_refs);
av_freep(&((MXFPackage *)*ctx)->name);
av_freep(&((MXFPackage *)*ctx)->comment_refs);
break;
case TaggedValue:
av_freep(&((MXFTaggedValue *)*ctx)->name);
av_freep(&((MXFTaggedValue *)*ctx)->value);
break;
case Track:
av_freep(&((MXFTrack *)*ctx)->name);
break;
case IndexTableSegment:
seg = (MXFIndexTableSegment *)*ctx;
av_freep(&seg->temporal_offset_entries);
av_freep(&seg->flag_entries);
av_freep(&seg->stream_offset_entries);
default:
break;
}
if (freectx)
av_freep(ctx);
}
static int64_t klv_decode_ber_length(AVIOContext *pb)
{
uint64_t size = avio_r8(pb);
if (size & 0x80) { /* long form */
int bytes_num = size & 0x7f;
/* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */
if (bytes_num > 8)
return AVERROR_INVALIDDATA;
size = 0;
while (bytes_num--)
size = size << 8 | avio_r8(pb);
}
if (size > INT64_MAX)
return AVERROR_INVALIDDATA;
return size;
}
static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size)
{
int i, b;
for (i = 0; i < size && !avio_feof(pb); i++) {
b = avio_r8(pb);
if (b == key[0])
i = 0;
else if (b != key[i])
i = -1;
}
return i == size;
}
static int klv_read_packet(KLVPacket *klv, AVIOContext *pb)
{
int64_t length, pos;
if (!mxf_read_sync(pb, mxf_klv_key, 4))
return AVERROR_INVALIDDATA;
klv->offset = avio_tell(pb) - 4;
memcpy(klv->key, mxf_klv_key, 4);
avio_read(pb, klv->key + 4, 12);
length = klv_decode_ber_length(pb);
if (length < 0)
return length;
klv->length = length;
pos = avio_tell(pb);
if (pos > INT64_MAX - length)
return AVERROR_INVALIDDATA;
klv->next_klv = pos + length;
return 0;
}
static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv, int body_sid)
{
int i;
for (i = 0; i < s->nb_streams; i++) {
MXFTrack *track = s->streams[i]->priv_data;
/* SMPTE 379M 7.3 */
if (track && (!body_sid || !track->body_sid || track->body_sid == body_sid) && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))
return i;
}
/* return 0 if only one stream, for OP Atom files with 0 as track number */
return s->nb_streams == 1 ? 0 : -1;
}
static int find_body_sid_by_offset(MXFContext *mxf, int64_t offset)
{
// we look for partition where the offset is placed
int a, b, m;
int64_t this_partition;
a = -1;
b = mxf->partitions_count;
while (b - a > 1) {
m = (a + b) >> 1;
this_partition = mxf->partitions[m].this_partition;
if (this_partition <= offset)
a = m;
else
b = m;
}
if (a == -1)
return 0;
return mxf->partitions[a].body_sid;
}
/* XXX: use AVBitStreamFilter */
static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)
{
const uint8_t *buf_ptr, *end_ptr;
uint8_t *data_ptr;
int i;
if (length > 61444) /* worst case PAL 1920 samples 8 channels */
return AVERROR_INVALIDDATA;
length = av_get_packet(pb, pkt, length);
if (length < 0)
return length;
data_ptr = pkt->data;
end_ptr = pkt->data + length;
buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */
for (; end_ptr - buf_ptr >= st->codecpar->channels * 4; ) {
for (i = 0; i < st->codecpar->channels; i++) {
uint32_t sample = bytestream_get_le32(&buf_ptr);
if (st->codecpar->bits_per_coded_sample == 24)
bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);
else
bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);
}
buf_ptr += 32 - st->codecpar->channels*4; // always 8 channels stored SMPTE 331M
}
av_shrink_packet(pkt, data_ptr - pkt->data);
return 0;
}
static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)
{
static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};
MXFContext *mxf = s->priv_data;
AVIOContext *pb = s->pb;
int64_t end = avio_tell(pb) + klv->length;
int64_t size;
uint64_t orig_size;
uint64_t plaintext_size;
uint8_t ivec[16];
uint8_t tmpbuf[16];
int index;
int body_sid;
if (!mxf->aesc && s->key && s->keylen == 16) {
mxf->aesc = av_aes_alloc();
if (!mxf->aesc)
return AVERROR(ENOMEM);
av_aes_init(mxf->aesc, s->key, 128, 1);
}
// crypto context
size = klv_decode_ber_length(pb);
if (size < 0)
return size;
avio_skip(pb, size);
// plaintext offset
klv_decode_ber_length(pb);
plaintext_size = avio_rb64(pb);
// source klv key
klv_decode_ber_length(pb);
avio_read(pb, klv->key, 16);
if (!IS_KLV_KEY(klv, mxf_essence_element_key))
return AVERROR_INVALIDDATA;
body_sid = find_body_sid_by_offset(mxf, klv->offset);
index = mxf_get_stream_index(s, klv, body_sid);
if (index < 0)
return AVERROR_INVALIDDATA;
// source size
klv_decode_ber_length(pb);
orig_size = avio_rb64(pb);
if (orig_size < plaintext_size)
return AVERROR_INVALIDDATA;
// enc. code
size = klv_decode_ber_length(pb);
if (size < 32 || size - 32 < orig_size)
return AVERROR_INVALIDDATA;
avio_read(pb, ivec, 16);
avio_read(pb, tmpbuf, 16);
if (mxf->aesc)
av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);
if (memcmp(tmpbuf, checkv, 16))
av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");
size -= 32;
size = av_get_packet(pb, pkt, size);
if (size < 0)
return size;
else if (size < plaintext_size)
return AVERROR_INVALIDDATA;
size -= plaintext_size;
if (mxf->aesc)
av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],
&pkt->data[plaintext_size], size >> 4, ivec, 1);
av_shrink_packet(pkt, orig_size);
pkt->stream_index = index;
avio_skip(pb, end - avio_tell(pb));
return 0;
}
static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
int item_num = avio_rb32(pb);
int item_len = avio_rb32(pb);
if (item_len != 18) {
avpriv_request_sample(pb, "Primer pack item length %d", item_len);
return AVERROR_PATCHWELCOME;
}
if (item_num > 65536 || item_num < 0) {
av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num);
return AVERROR_INVALIDDATA;
}
if (mxf->local_tags)
av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n");
av_free(mxf->local_tags);
mxf->local_tags_count = 0;
mxf->local_tags = av_calloc(item_num, item_len);
if (!mxf->local_tags)
return AVERROR(ENOMEM);
mxf->local_tags_count = item_num;
avio_read(pb, mxf->local_tags, item_num*item_len);
return 0;
}
static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
MXFPartition *partition, *tmp_part;
UID op;
uint64_t footer_partition;
uint32_t nb_essence_containers;
if (mxf->partitions_count >= INT_MAX / 2)
return AVERROR_INVALIDDATA;
tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions));
if (!tmp_part)
return AVERROR(ENOMEM);
mxf->partitions = tmp_part;
if (mxf->parsing_backward) {
/* insert the new partition pack in the middle
* this makes the entries in mxf->partitions sorted by offset */
memmove(&mxf->partitions[mxf->last_forward_partition+1],
&mxf->partitions[mxf->last_forward_partition],
(mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions));
partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition];
} else {
mxf->last_forward_partition++;
partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count];
}
memset(partition, 0, sizeof(*partition));
mxf->partitions_count++;
partition->pack_length = avio_tell(pb) - klv_offset + size;
partition->pack_ofs = klv_offset;
switch(uid[13]) {
case 2:
partition->type = Header;
break;
case 3:
partition->type = BodyPartition;
break;
case 4:
partition->type = Footer;
break;
default:
av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]);
return AVERROR_INVALIDDATA;
}
/* consider both footers to be closed (there is only Footer and CompleteFooter) */
partition->closed = partition->type == Footer || !(uid[14] & 1);
partition->complete = uid[14] > 2;
avio_skip(pb, 4);
partition->kag_size = avio_rb32(pb);
partition->this_partition = avio_rb64(pb);
partition->previous_partition = avio_rb64(pb);
footer_partition = avio_rb64(pb);
partition->header_byte_count = avio_rb64(pb);
partition->index_byte_count = avio_rb64(pb);
partition->index_sid = avio_rb32(pb);
partition->body_offset = avio_rb64(pb);
partition->body_sid = avio_rb32(pb);
if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) {
av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n");
return AVERROR_INVALIDDATA;
}
nb_essence_containers = avio_rb32(pb);
if (partition->this_partition &&
partition->previous_partition == partition->this_partition) {
av_log(mxf->fc, AV_LOG_ERROR,
"PreviousPartition equal to ThisPartition %"PRIx64"\n",
partition->previous_partition);
/* override with the actual previous partition offset */
if (!mxf->parsing_backward && mxf->last_forward_partition > 1) {
MXFPartition *prev =
mxf->partitions + mxf->last_forward_partition - 2;
partition->previous_partition = prev->this_partition;
}
/* if no previous body partition are found point to the header
* partition */
if (partition->previous_partition == partition->this_partition)
partition->previous_partition = 0;
av_log(mxf->fc, AV_LOG_ERROR,
"Overriding PreviousPartition with %"PRIx64"\n",
partition->previous_partition);
}
/* some files don't have FooterPartition set in every partition */
if (footer_partition) {
if (mxf->footer_partition && mxf->footer_partition != footer_partition) {
av_log(mxf->fc, AV_LOG_ERROR,
"inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n",
mxf->footer_partition, footer_partition);
} else {
mxf->footer_partition = footer_partition;
}
}
av_log(mxf->fc, AV_LOG_TRACE,
"PartitionPack: ThisPartition = 0x%"PRIX64
", PreviousPartition = 0x%"PRIX64", "
"FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n",
partition->this_partition,
partition->previous_partition, footer_partition,
partition->index_sid, partition->body_sid);
/* sanity check PreviousPartition if set */
//NOTE: this isn't actually enough, see mxf_seek_to_previous_partition()
if (partition->previous_partition &&
mxf->run_in + partition->previous_partition >= klv_offset) {
av_log(mxf->fc, AV_LOG_ERROR,
"PreviousPartition points to this partition or forward\n");
return AVERROR_INVALIDDATA;
}
if (op[12] == 1 && op[13] == 1) mxf->op = OP1a;
else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b;
else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c;
else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a;
else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b;
else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c;
else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a;
else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b;
else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c;
else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt;
else if (op[12] == 0x10) {
/* SMPTE 390m: "There shall be exactly one essence container"
* The following block deals with files that violate this, namely:
* 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a
* abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */
if (nb_essence_containers != 1) {
MXFOP op = nb_essence_containers ? OP1a : OPAtom;
/* only nag once */
if (!mxf->op)
av_log(mxf->fc, AV_LOG_WARNING,
"\"OPAtom\" with %"PRIu32" ECs - assuming %s\n",
nb_essence_containers,
op == OP1a ? "OP1a" : "OPAtom");
mxf->op = op;
} else
mxf->op = OPAtom;
} else {
av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]);
mxf->op = OP1a;
}
if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) {
av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ",
partition->kag_size);
if (mxf->op == OPSONYOpt)
partition->kag_size = 512;
else
partition->kag_size = 1;
av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size);
}
return 0;
}
static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)
{
MXFMetadataSet **tmp;
tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets));
if (!tmp)
return AVERROR(ENOMEM);
mxf->metadata_sets = tmp;
mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;
mxf->metadata_sets_count++;
return 0;
}
static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFCryptoContext *cryptocontext = arg;
if (size != 16)
return AVERROR_INVALIDDATA;
if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))
avio_read(pb, cryptocontext->source_container_ul, 16);
return 0;
}
static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count)
{
*count = avio_rb32(pb);
*refs = av_calloc(*count, sizeof(UID));
if (!*refs) {
*count = 0;
return AVERROR(ENOMEM);
}
avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */
avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID));
return 0;
}
static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be)
{
int ret;
size_t buf_size;
if (size < 0 || size > INT_MAX/2)
return AVERROR(EINVAL);
buf_size = size + size / 2 + 1;
*str = av_malloc(buf_size);
if (!*str)
return AVERROR(ENOMEM);
if (be)
ret = avio_get_str16be(pb, size, *str, buf_size);
else
ret = avio_get_str16le(pb, size, *str, buf_size);
if (ret < 0) {
av_freep(str);
return ret;
}
return ret;
}
#define READ_STR16(type, big_endian) \
static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \
{ \
return mxf_read_utf16_string(pb, size, str, big_endian); \
}
READ_STR16(be, 1)
READ_STR16(le, 0)
#undef READ_STR16
static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
switch (tag) {
case 0x1901:
if (mxf->packages_refs)
av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n");
av_free(mxf->packages_refs);
return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count);
case 0x1902:
av_free(mxf->essence_container_data_refs);
return mxf_read_strong_ref_array(pb, &mxf->essence_container_data_refs, &mxf->essence_container_data_count);
}
return 0;
}
static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFStructuralComponent *source_clip = arg;
switch(tag) {
case 0x0202:
source_clip->duration = avio_rb64(pb);
break;
case 0x1201:
source_clip->start_position = avio_rb64(pb);
break;
case 0x1101:
/* UMID, only get last 16 bytes */
avio_read(pb, source_clip->source_package_ul, 16);
avio_read(pb, source_clip->source_package_uid, 16);
break;
case 0x1102:
source_clip->source_track_id = avio_rb32(pb);
break;
}
return 0;
}
static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFTimecodeComponent *mxf_timecode = arg;
switch(tag) {
case 0x1501:
mxf_timecode->start_frame = avio_rb64(pb);
break;
case 0x1502:
mxf_timecode->rate = (AVRational){avio_rb16(pb), 1};
break;
case 0x1503:
mxf_timecode->drop_frame = avio_r8(pb);
break;
}
return 0;
}
static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFPulldownComponent *mxf_pulldown = arg;
switch(tag) {
case 0x0d01:
avio_read(pb, mxf_pulldown->input_segment_ref, 16);
break;
}
return 0;
}
static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFTrack *track = arg;
switch(tag) {
case 0x4801:
track->track_id = avio_rb32(pb);
break;
case 0x4804:
avio_read(pb, track->track_number, 4);
break;
case 0x4802:
mxf_read_utf16be_string(pb, size, &track->name);
break;
case 0x4b01:
track->edit_rate.num = avio_rb32(pb);
track->edit_rate.den = avio_rb32(pb);
break;
case 0x4803:
avio_read(pb, track->sequence_ref, 16);
break;
}
return 0;
}
static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFSequence *sequence = arg;
switch(tag) {
case 0x0202:
sequence->duration = avio_rb64(pb);
break;
case 0x0201:
avio_read(pb, sequence->data_definition_ul, 16);
break;
case 0x4b02:
sequence->origin = avio_r8(pb);
break;
case 0x1001:
return mxf_read_strong_ref_array(pb, &sequence->structural_components_refs,
&sequence->structural_components_count);
}
return 0;
}
static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFEssenceGroup *essence_group = arg;
switch (tag) {
case 0x0202:
essence_group->duration = avio_rb64(pb);
break;
case 0x0501:
return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs,
&essence_group->structural_components_count);
}
return 0;
}
static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFPackage *package = arg;
switch(tag) {
case 0x4403:
return mxf_read_strong_ref_array(pb, &package->tracks_refs,
&package->tracks_count);
case 0x4401:
/* UMID */
avio_read(pb, package->package_ul, 16);
avio_read(pb, package->package_uid, 16);
break;
case 0x4701:
avio_read(pb, package->descriptor_ref, 16);
break;
case 0x4402:
return mxf_read_utf16be_string(pb, size, &package->name);
case 0x4406:
return mxf_read_strong_ref_array(pb, &package->comment_refs,
&package->comment_count);
}
return 0;
}
static int mxf_read_essence_container_data(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFEssenceContainerData *essence_data = arg;
switch(tag) {
case 0x2701:
/* linked package umid UMID */
avio_read(pb, essence_data->package_ul, 16);
avio_read(pb, essence_data->package_uid, 16);
break;
case 0x3f06:
essence_data->index_sid = avio_rb32(pb);
break;
case 0x3f07:
essence_data->body_sid = avio_rb32(pb);
break;
}
return 0;
}
static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
{
int i, length;
segment->nb_index_entries = avio_rb32(pb);
length = avio_rb32(pb);
if(segment->nb_index_entries && length < 11)
return AVERROR_INVALIDDATA;
if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
!(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
!(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) {
av_freep(&segment->temporal_offset_entries);
av_freep(&segment->flag_entries);
return AVERROR(ENOMEM);
}
for (i = 0; i < segment->nb_index_entries; i++) {
if(avio_feof(pb))
return AVERROR_INVALIDDATA;
segment->temporal_offset_entries[i] = avio_r8(pb);
avio_r8(pb); /* KeyFrameOffset */
segment->flag_entries[i] = avio_r8(pb);
segment->stream_offset_entries[i] = avio_rb64(pb);
avio_skip(pb, length - 11);
}
return 0;
}
static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFIndexTableSegment *segment = arg;
switch(tag) {
case 0x3F05:
segment->edit_unit_byte_count = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);
break;
case 0x3F06:
segment->index_sid = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid);
break;
case 0x3F07:
segment->body_sid = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid);
break;
case 0x3F0A:
av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n");
return mxf_read_index_entry_array(pb, segment);
case 0x3F0B:
segment->index_edit_rate.num = avio_rb32(pb);
segment->index_edit_rate.den = avio_rb32(pb);
av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,
segment->index_edit_rate.den);
break;
case 0x3F0C:
segment->index_start_position = avio_rb64(pb);
av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position);
break;
case 0x3F0D:
segment->index_duration = avio_rb64(pb);
av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration);
break;
}
return 0;
}
static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)
{
int code, value, ofs = 0;
char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */
do {
code = avio_r8(pb);
value = avio_r8(pb);
av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code);
if (ofs <= 14) {
layout[ofs++] = code;
layout[ofs++] = value;
} else
break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */
} while (code != 0); /* SMPTE 377M E.2.46 */
ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);
}
static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFDescriptor *descriptor = arg;
int entry_count, entry_size;
switch(tag) {
case 0x3F01:
return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs,
&descriptor->sub_descriptors_count);
case 0x3002: /* ContainerDuration */
descriptor->duration = avio_rb64(pb);
break;
case 0x3004:
avio_read(pb, descriptor->essence_container_ul, 16);
break;
case 0x3005:
avio_read(pb, descriptor->codec_ul, 16);
break;
case 0x3006:
descriptor->linked_track_id = avio_rb32(pb);
break;
case 0x3201: /* PictureEssenceCoding */
avio_read(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3203:
descriptor->width = avio_rb32(pb);
break;
case 0x3202:
descriptor->height = avio_rb32(pb);
break;
case 0x320C:
descriptor->frame_layout = avio_r8(pb);
break;
case 0x320D:
entry_count = avio_rb32(pb);
entry_size = avio_rb32(pb);
if (entry_size == 4) {
if (entry_count > 0)
descriptor->video_line_map[0] = avio_rb32(pb);
else
descriptor->video_line_map[0] = 0;
if (entry_count > 1)
descriptor->video_line_map[1] = avio_rb32(pb);
else
descriptor->video_line_map[1] = 0;
} else
av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size);
break;
case 0x320E:
descriptor->aspect_ratio.num = avio_rb32(pb);
descriptor->aspect_ratio.den = avio_rb32(pb);
break;
case 0x3212:
descriptor->field_dominance = avio_r8(pb);
break;
case 0x3301:
descriptor->component_depth = avio_rb32(pb);
break;
case 0x3302:
descriptor->horiz_subsampling = avio_rb32(pb);
break;
case 0x3308:
descriptor->vert_subsampling = avio_rb32(pb);
break;
case 0x3D03:
descriptor->sample_rate.num = avio_rb32(pb);
descriptor->sample_rate.den = avio_rb32(pb);
break;
case 0x3D06: /* SoundEssenceCompression */
avio_read(pb, descriptor->essence_codec_ul, 16);
break;
case 0x3D07:
descriptor->channels = avio_rb32(pb);
break;
case 0x3D01:
descriptor->bits_per_sample = avio_rb32(pb);
break;
case 0x3401:
mxf_read_pixel_layout(pb, descriptor);
break;
default:
/* Private uid used by SONY C0023S01.mxf */
if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {
if (descriptor->extradata)
av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n");
av_free(descriptor->extradata);
descriptor->extradata_size = 0;
descriptor->extradata = av_malloc(size);
if (!descriptor->extradata)
return AVERROR(ENOMEM);
descriptor->extradata_size = size;
avio_read(pb, descriptor->extradata, size);
}
if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) {
uint32_t rsiz = avio_rb16(pb);
if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K ||
rsiz == FF_PROFILE_JPEG2000_DCINEMA_4K)
descriptor->pix_fmt = AV_PIX_FMT_XYZ12;
}
break;
}
return 0;
}
static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size)
{
MXFTaggedValue *tagged_value = arg;
uint8_t key[17];
if (size <= 17)
return 0;
avio_read(pb, key, 17);
/* TODO: handle other types of of indirect values */
if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) {
return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value);
} else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) {
return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value);
}
return 0;
}
static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFTaggedValue *tagged_value = arg;
switch (tag){
case 0x5001:
return mxf_read_utf16be_string(pb, size, &tagged_value->name);
case 0x5003:
return mxf_read_indirect_value(tagged_value, pb, size);
}
return 0;
}
/*
* Match an uid independently of the version byte and up to len common bytes
* Returns: boolean
*/
static int mxf_match_uid(const UID key, const UID uid, int len)
{
int i;
for (i = 0; i < len; i++) {
if (i != 7 && key[i] != uid[i])
return 0;
}
return 1;
}
static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid)
{
while (uls->uid[0]) {
if(mxf_match_uid(uls->uid, *uid, uls->matching_len))
break;
uls++;
}
return uls;
}
static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type)
{
int i;
if (!strong_ref)
return NULL;
for (i = 0; i < mxf->metadata_sets_count; i++) {
if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) &&
(type == AnyType || mxf->metadata_sets[i]->type == type)) {
return mxf->metadata_sets[i];
}
}
return NULL;
}
static const MXFCodecUL mxf_picture_essence_container_uls[] = {
// video essence container uls
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000, NULL, 14 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x10,0x60,0x01 }, 14, AV_CODEC_ID_H264, NULL, 15 }, /* H.264 */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x11,0x01,0x00 }, 14, AV_CODEC_ID_DNXHD, NULL, 14 }, /* VC-3 */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x12,0x01,0x00 }, 14, AV_CODEC_ID_VC1, NULL, 14 }, /* VC-1 */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x14,0x01,0x00 }, 14, AV_CODEC_ID_TIFF, NULL, 14 }, /* TIFF */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x15,0x01,0x00 }, 14, AV_CODEC_ID_DIRAC, NULL, 14 }, /* VC-2 */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1b,0x01,0x00 }, 14, AV_CODEC_ID_CFHD, NULL, 14 }, /* VC-5 */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 }, 14, AV_CODEC_ID_PRORES, NULL, 14 }, /* ProRes */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO, NULL, 15 }, /* MPEG-ES */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO, NULL, 15, D10D11Wrap }, /* SMPTE D-10 mapping */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO, NULL, 15 }, /* DV 625 25mbps */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO, NULL, 15, RawVWrap }, /* uncompressed picture */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX },
{ { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
/* EC ULs for intra-only formats */
static const MXFCodecUL mxf_intra_only_essence_container_uls[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 mappings */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
/* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */
static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG 2000 code stream */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
/* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */
static const MXFCodecUL mxf_intra_only_picture_coded_width[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 },
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 },
};
static const MXFCodecUL mxf_sound_essence_container_uls[] = {
// sound essence container uls
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE, NULL, 14, RawAWrap }, /* BWF */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2, NULL, 15 }, /* MPEG-ES */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE, NULL, 13 }, /* D-10 Mapping 50Mbps PAL Extended Template */
{ { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG-2 AAC ADTS (legacy) */
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
static const MXFCodecUL mxf_data_essence_container_uls[] = {
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0d,0x00,0x00 }, 16, AV_CODEC_ID_NONE, "vbi_smpte_436M", 11 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, AV_CODEC_ID_NONE, "vbi_vanc_smpte_436M", 11 },
{ { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x13,0x01,0x01 }, 16, AV_CODEC_ID_TTML },
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE },
};
static MXFWrappingScheme mxf_get_wrapping_kind(UID *essence_container_ul)
{
int val;
const MXFCodecUL *codec_ul;
codec_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
if (!codec_ul->uid[0])
codec_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
if (!codec_ul->uid[0])
codec_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
if (!codec_ul->uid[0] || !codec_ul->wrapping_indicator_pos)
return UnknownWrapped;
val = (*essence_container_ul)[codec_ul->wrapping_indicator_pos];
switch (codec_ul->wrapping_indicator_type) {
case RawVWrap:
val = val % 4;
break;
case RawAWrap:
if (val == 0x03 || val == 0x04)
val -= 0x02;
break;
case D10D11Wrap:
if (val == 0x02)
val = 0x01;
break;
}
if (val == 0x01)
return FrameWrapped;
if (val == 0x02)
return ClipWrapped;
return UnknownWrapped;
}
static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)
{
int i, j, nb_segments = 0;
MXFIndexTableSegment **unsorted_segments;
int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;
/* count number of segments, allocate arrays and copy unsorted segments */
for (i = 0; i < mxf->metadata_sets_count; i++)
if (mxf->metadata_sets[i]->type == IndexTableSegment)
nb_segments++;
if (!nb_segments)
return AVERROR_INVALIDDATA;
if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) ||
!(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) {
av_freep(sorted_segments);
av_free(unsorted_segments);
return AVERROR(ENOMEM);
}
for (i = j = 0; i < mxf->metadata_sets_count; i++)
if (mxf->metadata_sets[i]->type == IndexTableSegment)
unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];
*nb_sorted_segments = 0;
/* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */
for (i = 0; i < nb_segments; i++) {
int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;
uint64_t best_index_duration = 0;
for (j = 0; j < nb_segments; j++) {
MXFIndexTableSegment *s = unsorted_segments[j];
/* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.
* We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.
* If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have.
*/
if ((i == 0 ||
s->body_sid > last_body_sid ||
s->body_sid == last_body_sid && s->index_sid > last_index_sid ||
s->body_sid == last_body_sid && s->index_sid == last_index_sid && s->index_start_position > last_index_start) &&
(best == -1 ||
s->body_sid < best_body_sid ||
s->body_sid == best_body_sid && s->index_sid < best_index_sid ||
s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position < best_index_start ||
s->body_sid == best_body_sid && s->index_sid == best_index_sid && s->index_start_position == best_index_start && s->index_duration > best_index_duration)) {
best = j;
best_body_sid = s->body_sid;
best_index_sid = s->index_sid;
best_index_start = s->index_start_position;
best_index_duration = s->index_duration;
}
}
/* no suitable entry found -> we're done */
if (best == -1)
break;
(*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];
last_body_sid = best_body_sid;
last_index_sid = best_index_sid;
last_index_start = best_index_start;
}
av_free(unsorted_segments);
return 0;
}
/**
* Computes the absolute file offset of the given essence container offset
*/
static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out, MXFPartition **partition_out)
{
MXFPartition *last_p = NULL;
int a, b, m, m0;
if (offset < 0)
return AVERROR(EINVAL);
a = -1;
b = mxf->partitions_count;
while (b - a > 1) {
m0 = m = (a + b) >> 1;
while (m < b && mxf->partitions[m].body_sid != body_sid)
m++;
if (m < b && mxf->partitions[m].body_offset <= offset)
a = m;
else
b = m0;
}
if (a >= 0)
last_p = &mxf->partitions[a];
if (last_p && (!last_p->essence_length || last_p->essence_length > (offset - last_p->body_offset))) {
*offset_out = last_p->essence_offset + (offset - last_p->body_offset);
if (partition_out)
*partition_out = last_p;
return 0;
}
av_log(mxf->fc, AV_LOG_ERROR,
"failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n",
offset, body_sid);
return AVERROR_INVALIDDATA;
}
/**
* Returns the end position of the essence container with given BodySID, or zero if unknown
*/
static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid)
{
int x;
int64_t ret = 0;
for (x = 0; x < mxf->partitions_count; x++) {
MXFPartition *p = &mxf->partitions[x];
if (p->body_sid != body_sid)
continue;
if (!p->essence_length)
return 0;
ret = p->essence_offset + p->essence_length;
}
return ret;
}
/* EditUnit -> absolute offset */
static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, AVRational edit_rate, int64_t *edit_unit_out, int64_t *offset_out, MXFPartition **partition_out, int nag)
{
int i;
int64_t offset_temp = 0;
edit_unit = av_rescale_q(edit_unit, index_table->segments[0]->index_edit_rate, edit_rate);
for (i = 0; i < index_table->nb_segments; i++) {
MXFIndexTableSegment *s = index_table->segments[i];
edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */
if (edit_unit < s->index_start_position + s->index_duration) {
int64_t index = edit_unit - s->index_start_position;
if (s->edit_unit_byte_count)
offset_temp += s->edit_unit_byte_count * index;
else if (s->nb_index_entries) {
if (s->nb_index_entries == 2 * s->index_duration + 1)
index *= 2; /* Avid index */
if (index < 0 || index >= s->nb_index_entries) {
av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n",
index_table->index_sid, s->index_start_position);
return AVERROR_INVALIDDATA;
}
offset_temp = s->stream_offset_entries[index];
} else {
av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n",
index_table->index_sid, s->index_start_position);
return AVERROR_INVALIDDATA;
}
if (edit_unit_out)
*edit_unit_out = av_rescale_q(edit_unit, edit_rate, s->index_edit_rate);
return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out, partition_out);
} else {
/* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */
offset_temp += s->edit_unit_byte_count * s->index_duration;
}
}
if (nag)
av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid);
return AVERROR_INVALIDDATA;
}
static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table)
{
int i, j, x;
int8_t max_temporal_offset = -128;
uint8_t *flags;
/* first compute how many entries we have */
for (i = 0; i < index_table->nb_segments; i++) {
MXFIndexTableSegment *s = index_table->segments[i];
if (!s->nb_index_entries) {
index_table->nb_ptses = 0;
return 0; /* no TemporalOffsets */
}
if (s->index_duration > INT_MAX - index_table->nb_ptses) {
index_table->nb_ptses = 0;
av_log(mxf->fc, AV_LOG_ERROR, "ignoring IndexSID %d, duration is too large\n", s->index_sid);
return 0;
}
index_table->nb_ptses += s->index_duration;
}
/* paranoid check */
if (index_table->nb_ptses <= 0)
return 0;
if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) ||
!(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) ||
!(index_table->offsets = av_calloc(index_table->nb_ptses, sizeof(int8_t))) ||
!(flags = av_calloc(index_table->nb_ptses, sizeof(uint8_t)))) {
av_freep(&index_table->ptses);
av_freep(&index_table->fake_index);
av_freep(&index_table->offsets);
return AVERROR(ENOMEM);
}
/* we may have a few bad TemporalOffsets
* make sure the corresponding PTSes don't have the bogus value 0 */
for (x = 0; x < index_table->nb_ptses; x++)
index_table->ptses[x] = AV_NOPTS_VALUE;
/**
* We have this:
*
* x TemporalOffset
* 0: 0
* 1: 1
* 2: 1
* 3: -2
* 4: 1
* 5: 1
* 6: -2
*
* We want to transform it into this:
*
* x DTS PTS
* 0: -1 0
* 1: 0 3
* 2: 1 1
* 3: 2 2
* 4: 3 6
* 5: 4 4
* 6: 5 5
*
* We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses,
* then settings mxf->first_dts = -max(TemporalOffset[x]).
* The latter makes DTS <= PTS.
*/
for (i = x = 0; i < index_table->nb_segments; i++) {
MXFIndexTableSegment *s = index_table->segments[i];
int index_delta = 1;
int n = s->nb_index_entries;
if (s->nb_index_entries == 2 * s->index_duration + 1) {
index_delta = 2; /* Avid index */
/* ignore the last entry - it's the size of the essence container */
n--;
}
for (j = 0; j < n; j += index_delta, x++) {
int offset = s->temporal_offset_entries[j] / index_delta;
int index = x + offset;
if (x >= index_table->nb_ptses) {
av_log(mxf->fc, AV_LOG_ERROR,
"x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n",
s->nb_index_entries, s->index_duration);
break;
}
flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0;
if (index < 0 || index >= index_table->nb_ptses) {
av_log(mxf->fc, AV_LOG_ERROR,
"index entry %i + TemporalOffset %i = %i, which is out of bounds\n",
x, offset, index);
continue;
}
index_table->offsets[x] = offset;
index_table->ptses[index] = x;
max_temporal_offset = FFMAX(max_temporal_offset, offset);
}
}
/* calculate the fake index table in display order */
for (x = 0; x < index_table->nb_ptses; x++) {
index_table->fake_index[x].timestamp = x;
if (index_table->ptses[x] != AV_NOPTS_VALUE)
index_table->fake_index[index_table->ptses[x]].flags = flags[x];
}
av_freep(&flags);
index_table->first_dts = -max_temporal_offset;
return 0;
}
/**
* Sorts and collects index table segments into index tables.
* Also computes PTSes if possible.
*/
static int mxf_compute_index_tables(MXFContext *mxf)
{
int i, j, k, ret, nb_sorted_segments;
MXFIndexTableSegment **sorted_segments = NULL;
if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) ||
nb_sorted_segments <= 0) {
av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n");
return 0;
}
/* sanity check and count unique BodySIDs/IndexSIDs */
for (i = 0; i < nb_sorted_segments; i++) {
if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid)
mxf->nb_index_tables++;
else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) {
av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n");
ret = AVERROR_INVALIDDATA;
goto finish_decoding_index;
}
}
mxf->index_tables = av_mallocz_array(mxf->nb_index_tables,
sizeof(*mxf->index_tables));
if (!mxf->index_tables) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n");
ret = AVERROR(ENOMEM);
goto finish_decoding_index;
}
/* distribute sorted segments to index tables */
for (i = j = 0; i < nb_sorted_segments; i++) {
if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) {
/* next IndexSID */
j++;
}
mxf->index_tables[j].nb_segments++;
}
for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) {
MXFIndexTable *t = &mxf->index_tables[j];
MXFTrack *mxf_track = NULL;
t->segments = av_mallocz_array(t->nb_segments,
sizeof(*t->segments));
if (!t->segments) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment"
" pointer array\n");
ret = AVERROR(ENOMEM);
goto finish_decoding_index;
}
if (sorted_segments[i]->index_start_position)
av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n",
sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position);
memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*));
t->index_sid = sorted_segments[i]->index_sid;
t->body_sid = sorted_segments[i]->body_sid;
if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0)
goto finish_decoding_index;
for (k = 0; k < mxf->fc->nb_streams; k++) {
MXFTrack *track = mxf->fc->streams[k]->priv_data;
if (track && track->index_sid == t->index_sid) {
mxf_track = track;
break;
}
}
/* fix zero IndexDurations */
for (k = 0; k < t->nb_segments; k++) {
if (!t->segments[k]->index_edit_rate.num || !t->segments[k]->index_edit_rate.den) {
av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has invalid IndexEditRate\n",
t->index_sid, k);
if (mxf_track)
t->segments[k]->index_edit_rate = mxf_track->edit_rate;
}
if (t->segments[k]->index_duration)
continue;
if (t->nb_segments > 1)
av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n",
t->index_sid, k);
if (!mxf_track) {
av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n");
break;
}
/* assume the first stream's duration is reasonable
* leave index_duration = 0 on further segments in case we have any (unlikely)
*/
t->segments[k]->index_duration = mxf_track->original_duration;
break;
}
}
ret = 0;
finish_decoding_index:
av_free(sorted_segments);
return ret;
}
static int mxf_is_intra_only(MXFDescriptor *descriptor)
{
return mxf_get_codec_ul(mxf_intra_only_essence_container_uls,
&descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE ||
mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls,
&descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE;
}
static int mxf_uid_to_str(UID uid, char **str)
{
int i;
char *p;
p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1);
if (!p)
return AVERROR(ENOMEM);
for (i = 0; i < sizeof(UID); i++) {
snprintf(p, 2 + 1, "%.2x", uid[i]);
p += 2;
if (i == 3 || i == 5 || i == 7 || i == 9) {
snprintf(p, 1 + 1, "-");
p++;
}
}
return 0;
}
static int mxf_umid_to_str(UID ul, UID uid, char **str)
{
int i;
char *p;
p = *str = av_mallocz(sizeof(UID) * 4 + 2 + 1);
if (!p)
return AVERROR(ENOMEM);
snprintf(p, 2 + 1, "0x");
p += 2;
for (i = 0; i < sizeof(UID); i++) {
snprintf(p, 2 + 1, "%.2X", ul[i]);
p += 2;
}
for (i = 0; i < sizeof(UID); i++) {
snprintf(p, 2 + 1, "%.2X", uid[i]);
p += 2;
}
return 0;
}
static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package)
{
char *str;
int ret;
if (!package)
return 0;
if ((ret = mxf_umid_to_str(package->package_ul, package->package_uid, &str)) < 0)
return ret;
av_dict_set(pm, key, str, AV_DICT_DONT_STRDUP_VAL);
return 0;
}
static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc)
{
char buf[AV_TIMECODE_STR_SIZE];
av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0);
return 0;
}
static MXFTimecodeComponent* mxf_resolve_timecode_component(MXFContext *mxf, UID *strong_ref)
{
MXFStructuralComponent *component = NULL;
MXFPulldownComponent *pulldown = NULL;
component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
if (!component)
return NULL;
switch (component->type) {
case TimecodeComponent:
return (MXFTimecodeComponent*)component;
case PulldownComponent: /* timcode component may be located on a pulldown component */
pulldown = (MXFPulldownComponent*)component;
return mxf_resolve_strong_ref(mxf, &pulldown->input_segment_ref, TimecodeComponent);
default:
break;
}
return NULL;
}
static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_ul, UID package_uid)
{
MXFPackage *package = NULL;
int i;
for (i = 0; i < mxf->packages_count; i++) {
package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage);
if (!package)
continue;
if (!memcmp(package->package_ul, package_ul, 16) && !memcmp(package->package_uid, package_uid, 16))
return package;
}
return NULL;
}
static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id)
{
MXFDescriptor *sub_descriptor = NULL;
int i;
if (!descriptor)
return NULL;
if (descriptor->type == MultipleDescriptor) {
for (i = 0; i < descriptor->sub_descriptors_count; i++) {
sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], Descriptor);
if (!sub_descriptor) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n");
continue;
}
if (sub_descriptor->linked_track_id == track_id) {
return sub_descriptor;
}
}
} else if (descriptor->type == Descriptor)
return descriptor;
return NULL;
}
static MXFStructuralComponent* mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group)
{
MXFStructuralComponent *component = NULL;
MXFPackage *package = NULL;
MXFDescriptor *descriptor = NULL;
int i;
if (!essence_group || !essence_group->structural_components_count)
return NULL;
/* essence groups contains multiple representations of the same media,
this return the first components with a valid Descriptor typically index 0 */
for (i =0; i < essence_group->structural_components_count; i++){
component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip);
if (!component)
continue;
if (!(package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid)))
continue;
descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor);
if (descriptor)
return component;
}
return NULL;
}
static MXFStructuralComponent* mxf_resolve_sourceclip(MXFContext *mxf, UID *strong_ref)
{
MXFStructuralComponent *component = NULL;
component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType);
if (!component)
return NULL;
switch (component->type) {
case SourceClip:
return component;
case EssenceGroup:
return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component);
default:
break;
}
return NULL;
}
static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package)
{
MXFTaggedValue *tag;
int size, i;
char *key = NULL;
for (i = 0; i < package->comment_count; i++) {
tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue);
if (!tag || !tag->name || !tag->value)
continue;
size = strlen(tag->name) + 8 + 1;
key = av_mallocz(size);
if (!key)
return AVERROR(ENOMEM);
snprintf(key, size, "comment_%s", tag->name);
av_dict_set(pm, key, tag->value, AV_DICT_DONT_STRDUP_KEY);
}
return 0;
}
static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st)
{
MXFPackage *physical_package = NULL;
MXFTrack *physical_track = NULL;
MXFStructuralComponent *sourceclip = NULL;
MXFTimecodeComponent *mxf_tc = NULL;
int i, j, k;
AVTimecode tc;
int flags;
int64_t start_position;
for (i = 0; i < source_track->sequence->structural_components_count; i++) {
sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);
if (!sourceclip)
continue;
if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_ul, sourceclip->source_package_uid)))
break;
mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package);
/* the name of physical source package is name of the reel or tape */
if (physical_package->name && physical_package->name[0])
av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);
/* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track
* to the start_frame of the timecode component located on one of the tracks of the physical source package.
*/
for (j = 0; j < physical_package->tracks_count; j++) {
if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
continue;
}
if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
continue;
}
if (physical_track->edit_rate.num <= 0 ||
physical_track->edit_rate.den <= 0) {
av_log(mxf->fc, AV_LOG_WARNING,
"Invalid edit rate (%d/%d) found on structural"
" component #%d, defaulting to 25/1\n",
physical_track->edit_rate.num,
physical_track->edit_rate.den, i);
physical_track->edit_rate = (AVRational){25, 1};
}
for (k = 0; k < physical_track->sequence->structural_components_count; k++) {
if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k])))
continue;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
/* scale sourceclip start_position to match physical track edit rate */
start_position = av_rescale_q(sourceclip->start_position,
physical_track->edit_rate,
source_track->edit_rate);
if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);
return 0;
}
}
}
}
return 0;
}
static int mxf_add_metadata_stream(MXFContext *mxf, MXFTrack *track)
{
MXFStructuralComponent *component = NULL;
const MXFCodecUL *codec_ul = NULL;
MXFPackage tmp_package;
AVStream *st;
int j;
for (j = 0; j < track->sequence->structural_components_count; j++) {
component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]);
if (!component)
continue;
break;
}
if (!component)
return 0;
st = avformat_new_stream(mxf->fc, NULL);
if (!st) {
av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n");
return AVERROR(ENOMEM);
}
st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
st->codecpar->codec_id = AV_CODEC_ID_NONE;
st->id = track->track_id;
memcpy(&tmp_package.package_ul, component->source_package_ul, 16);
memcpy(&tmp_package.package_uid, component->source_package_uid, 16);
mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package);
if (track->name && track->name[0])
av_dict_set(&st->metadata, "track_name", track->name, 0);
codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &track->sequence->data_definition_ul);
av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0);
return 0;
}
static int mxf_parse_structural_metadata(MXFContext *mxf)
{
MXFPackage *material_package = NULL;
int i, j, k, ret;
av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count);
/* TODO: handle multiple material packages (OP3x) */
for (i = 0; i < mxf->packages_count; i++) {
material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage);
if (material_package) break;
}
if (!material_package) {
av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n");
return AVERROR_INVALIDDATA;
}
mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package);
if (material_package->name && material_package->name[0])
av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0);
mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package);
for (i = 0; i < material_package->tracks_count; i++) {
MXFPackage *source_package = NULL;
MXFTrack *material_track = NULL;
MXFTrack *source_track = NULL;
MXFTrack *temp_track = NULL;
MXFDescriptor *descriptor = NULL;
MXFStructuralComponent *component = NULL;
MXFTimecodeComponent *mxf_tc = NULL;
UID *essence_container_ul = NULL;
const MXFCodecUL *codec_ul = NULL;
const MXFCodecUL *container_ul = NULL;
const MXFCodecUL *pix_fmt_ul = NULL;
AVStream *st;
AVTimecode tc;
int flags;
if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n");
continue;
}
if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) {
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
}
}
if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n");
continue;
}
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent);
if (!component)
continue;
mxf_tc = (MXFTimecodeComponent*)component;
flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;
if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) {
mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc);
break;
}
}
/* TODO: handle multiple source clips, only finds first valid source clip */
if(material_track->sequence->structural_components_count > 1)
av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n",
material_track->track_id, material_track->sequence->structural_components_count);
for (j = 0; j < material_track->sequence->structural_components_count; j++) {
component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]);
if (!component)
continue;
source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid);
if (!source_package) {
av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id);
continue;
}
for (k = 0; k < source_package->tracks_count; k++) {
if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
if (temp_track->track_id == component->source_track_id) {
source_track = temp_track;
break;
}
}
if (!source_track) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id);
break;
}
for (k = 0; k < mxf->essence_container_data_count; k++) {
MXFEssenceContainerData *essence_data;
if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) {
av_log(mxf, AV_LOG_TRACE, "could not resolve essence container data strong ref\n");
continue;
}
if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {
source_track->body_sid = essence_data->body_sid;
source_track->index_sid = essence_data->index_sid;
break;
}
}
if(source_track && component)
break;
}
if (!source_track || !component || !source_package) {
if((ret = mxf_add_metadata_stream(mxf, material_track)))
goto fail_and_free;
continue;
}
if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) {
av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");
ret = AVERROR_INVALIDDATA;
goto fail_and_free;
}
/* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf
* This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */
if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) {
av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id);
continue;
}
st = avformat_new_stream(mxf->fc, NULL);
if (!st) {
av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n");
ret = AVERROR(ENOMEM);
goto fail_and_free;
}
st->id = material_track->track_id;
st->priv_data = source_track;
source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType);
descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id);
/* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many
* frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */
if (descriptor && descriptor->duration != AV_NOPTS_VALUE)
source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration);
else
source_track->original_duration = st->duration = component->duration;
if (st->duration == -1)
st->duration = AV_NOPTS_VALUE;
st->start_time = component->start_position;
if (material_track->edit_rate.num <= 0 ||
material_track->edit_rate.den <= 0) {
av_log(mxf->fc, AV_LOG_WARNING,
"Invalid edit rate (%d/%d) found on stream #%d, "
"defaulting to 25/1\n",
material_track->edit_rate.num,
material_track->edit_rate.den, st->index);
material_track->edit_rate = (AVRational){25, 1};
}
avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num);
/* ensure SourceTrack EditRate == MaterialTrack EditRate since only
* the former is accessible via st->priv_data */
source_track->edit_rate = material_track->edit_rate;
PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul);
codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul);
st->codecpar->codec_type = codec_ul->id;
if (!descriptor) {
av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index);
continue;
}
PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul);
PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul);
essence_container_ul = &descriptor->essence_container_ul;
source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul);
if (source_track->wrapping == UnknownWrapped)
av_log(mxf->fc, AV_LOG_INFO, "wrapping of stream %d is unknown\n", st->index);
/* HACK: replacing the original key with mxf_encrypted_essence_container
* is not allowed according to s429-6, try to find correct information anyway */
if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) {
av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n");
for (k = 0; k < mxf->metadata_sets_count; k++) {
MXFMetadataSet *metadata = mxf->metadata_sets[k];
if (metadata->type == CryptoContext) {
essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul;
break;
}
}
}
/* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul);
st->codecpar->codec_id = (enum AVCodecID)codec_ul->id;
}
av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ",
avcodec_get_name(st->codecpar->codec_id));
for (k = 0; k < 16; k++) {
av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x",
descriptor->essence_codec_ul[k]);
if (!(k+1 & 19) || k == 5)
av_log(mxf->fc, AV_LOG_VERBOSE, ".");
}
av_log(mxf->fc, AV_LOG_VERBOSE, "\n");
mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package);
if (source_package->name && source_package->name[0])
av_dict_set(&st->metadata, "file_package_name", source_package->name, 0);
if (material_track->name && material_track->name[0])
av_dict_set(&st->metadata, "track_name", material_track->name, 0);
mxf_parse_physical_source_package(mxf, source_track, st);
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
source_track->intra_only = mxf_is_intra_only(descriptor);
container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
st->codecpar->width = descriptor->width;
st->codecpar->height = descriptor->height; /* Field height, not frame height */
switch (descriptor->frame_layout) {
case FullFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
break;
case OneField:
/* Every other line is stored and needs to be duplicated. */
av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n");
break; /* The correct thing to do here is fall through, but by breaking we might be
able to decode some streams at half the vertical resolution, rather than not al all.
It's also for compatibility with the old behavior. */
case MixedFields:
break;
case SegmentedFrame:
st->codecpar->field_order = AV_FIELD_PROGRESSIVE;
case SeparateFields:
av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n",
descriptor->video_line_map[0], descriptor->video_line_map[1],
descriptor->field_dominance);
if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) {
/* Detect coded field order from VideoLineMap:
* (even, even) => bottom field coded first
* (even, odd) => top field coded first
* (odd, even) => top field coded first
* (odd, odd) => bottom field coded first
*/
if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_TT;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_TB;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
} else {
switch (descriptor->field_dominance) {
case MXF_FIELD_DOMINANCE_DEFAULT:
case MXF_FIELD_DOMINANCE_FF:
st->codecpar->field_order = AV_FIELD_BB;
break;
case MXF_FIELD_DOMINANCE_FL:
st->codecpar->field_order = AV_FIELD_BT;
break;
default:
avpriv_request_sample(mxf->fc,
"Field dominance %d support",
descriptor->field_dominance);
}
}
}
/* Turn field height into frame height. */
st->codecpar->height *= 2;
break;
default:
av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout);
}
if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) {
st->codecpar->format = descriptor->pix_fmt;
if (st->codecpar->format == AV_PIX_FMT_NONE) {
pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls,
&descriptor->essence_codec_ul);
st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id;
if (st->codecpar->format== AV_PIX_FMT_NONE) {
st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls,
&descriptor->essence_codec_ul)->id;
if (!st->codecpar->codec_tag) {
/* support files created before RP224v10 by defaulting to UYVY422
if subsampling is 4:2:2 and component depth is 8-bit */
if (descriptor->horiz_subsampling == 2 &&
descriptor->vert_subsampling == 1 &&
descriptor->component_depth == 8) {
st->codecpar->format = AV_PIX_FMT_UYVY422;
}
}
}
}
}
st->need_parsing = AVSTREAM_PARSE_HEADERS;
if (material_track->sequence->origin) {
av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0);
}
if (source_track->sequence->origin) {
av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0);
}
if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den)
st->display_aspect_ratio = descriptor->aspect_ratio;
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul);
/* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */
if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE))
st->codecpar->codec_id = (enum AVCodecID)container_ul->id;
st->codecpar->channels = descriptor->channels;
st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample;
if (descriptor->sample_rate.den > 0) {
st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den;
avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num);
} else {
av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) "
"found for stream #%d, time base forced to 1/48000\n",
descriptor->sample_rate.num, descriptor->sample_rate.den,
st->index);
avpriv_set_pts_info(st, 64, 1, 48000);
}
/* if duration is set, rescale it from EditRate to SampleRate */
if (st->duration != AV_NOPTS_VALUE)
st->duration = av_rescale_q(st->duration,
av_inv_q(material_track->edit_rate),
st->time_base);
/* TODO: implement AV_CODEC_ID_RAWAUDIO */
if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE;
else if (descriptor->bits_per_sample == 32)
st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE;
} else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
st->need_parsing = AVSTREAM_PARSE_FULL;
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
enum AVMediaType type;
container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul);
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
st->codecpar->codec_id = container_ul->id;
type = avcodec_get_type(st->codecpar->codec_id);
if (type == AVMEDIA_TYPE_SUBTITLE)
st->codecpar->codec_type = type;
if (container_ul->desc)
av_dict_set(&st->metadata, "data_type", container_ul->desc, 0);
}
if (descriptor->extradata) {
if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) {
memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size);
}
} else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width,
&descriptor->essence_codec_ul)->id;
if (coded_width)
st->codecpar->width = coded_width;
ret = ff_generate_avci_extradata(st);
if (ret < 0)
return ret;
}
if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) {
/* TODO: decode timestamps */
st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
}
}
ret = 0;
fail_and_free:
return ret;
}
static int64_t mxf_timestamp_to_int64(uint64_t timestamp)
{
struct tm time = { 0 };
time.tm_year = (timestamp >> 48) - 1900;
time.tm_mon = (timestamp >> 40 & 0xFF) - 1;
time.tm_mday = (timestamp >> 32 & 0xFF);
time.tm_hour = (timestamp >> 24 & 0xFF);
time.tm_min = (timestamp >> 16 & 0xFF);
time.tm_sec = (timestamp >> 8 & 0xFF);
/* msvcrt versions of strftime calls the invalid parameter handler
* (aborting the process if one isn't set) if the parameters are out
* of range. */
time.tm_mon = av_clip(time.tm_mon, 0, 11);
time.tm_mday = av_clip(time.tm_mday, 1, 31);
time.tm_hour = av_clip(time.tm_hour, 0, 23);
time.tm_min = av_clip(time.tm_min, 0, 59);
time.tm_sec = av_clip(time.tm_sec, 0, 59);
return (int64_t)av_timegm(&time) * 1000000;
}
#define SET_STR_METADATA(pb, name, str) do { \
if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \
return ret; \
av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
} while (0)
#define SET_UID_METADATA(pb, name, var, str) do { \
avio_read(pb, var, 16); \
if ((ret = mxf_uid_to_str(var, &str)) < 0) \
return ret; \
av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \
} while (0)
#define SET_TS_METADATA(pb, name, var, str) do { \
var = avio_rb64(pb); \
if ((ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var)) < 0)) \
return ret; \
} while (0)
static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
AVFormatContext *s = mxf->fc;
int ret;
UID uid = { 0 };
char *str = NULL;
uint64_t ts;
switch (tag) {
case 0x3C01:
SET_STR_METADATA(pb, "company_name", str);
break;
case 0x3C02:
SET_STR_METADATA(pb, "product_name", str);
break;
case 0x3C04:
SET_STR_METADATA(pb, "product_version", str);
break;
case 0x3C05:
SET_UID_METADATA(pb, "product_uid", uid, str);
break;
case 0x3C06:
SET_TS_METADATA(pb, "modification_date", ts, str);
break;
case 0x3C08:
SET_STR_METADATA(pb, "application_platform", str);
break;
case 0x3C09:
SET_UID_METADATA(pb, "generation_uid", uid, str);
break;
case 0x3C0A:
SET_UID_METADATA(pb, "uid", uid, str);
break;
}
return 0;
}
static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)
{
MXFContext *mxf = arg;
AVFormatContext *s = mxf->fc;
int ret;
char *str = NULL;
if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) {
SET_STR_METADATA(pb, "project_name", str);
}
return 0;
}
static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = {
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence },
{ { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup},
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5b,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VBI - SMPTE 436M */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VANC/VBI - SMPTE 436M */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x64,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* DC Timed Text Descriptor */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment },
{ { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x23,0x00 }, mxf_read_essence_container_data, sizeof(MXFEssenceContainerData), EssenceContainerData },
{ { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType },
};
static int mxf_metadataset_init(MXFMetadataSet *ctx, enum MXFMetadataSetType type)
{
switch (type){
case MultipleDescriptor:
case Descriptor:
((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE;
((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE;
break;
default:
break;
}
return 0;
}
static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type)
{
AVIOContext *pb = mxf->fc->pb;
MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf;
uint64_t klv_end = avio_tell(pb) + klv->length;
if (!ctx)
return AVERROR(ENOMEM);
mxf_metadataset_init(ctx, type);
while (avio_tell(pb) + 4 < klv_end && !avio_feof(pb)) {
int ret;
int tag = avio_rb16(pb);
int size = avio_rb16(pb); /* KLV specified by 0x53 */
uint64_t next = avio_tell(pb) + size;
UID uid = {0};
av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size);
if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */
av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag);
continue;
}
if (tag > 0x7FFF) { /* dynamic tag */
int i;
for (i = 0; i < mxf->local_tags_count; i++) {
int local_tag = AV_RB16(mxf->local_tags+i*18);
if (local_tag == tag) {
memcpy(uid, mxf->local_tags+i*18+2, 16);
av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag);
PRINT_KEY(mxf->fc, "uid", uid);
}
}
}
if (ctx_size && tag == 0x3C0A) {
avio_read(pb, ctx->uid, 16);
} else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) {
mxf_free_metadataset(&ctx, !!ctx_size);
return ret;
}
/* Accept the 64k local set limit being exceeded (Avid). Don't accept
* it extending past the end of the KLV though (zzuf5.mxf). */
if (avio_tell(pb) > klv_end) {
if (ctx_size) {
ctx->type = type;
mxf_free_metadataset(&ctx, !!ctx_size);
}
av_log(mxf->fc, AV_LOG_ERROR,
"local tag %#04x extends past end of local set @ %#"PRIx64"\n",
tag, klv->offset);
return AVERROR_INVALIDDATA;
} else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */
avio_seek(pb, next, SEEK_SET);
}
if (ctx_size) ctx->type = type;
return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0;
}
/**
* Matches any partition pack key, in other words:
* - HeaderPartition
* - BodyPartition
* - FooterPartition
* @return non-zero if the key is a partition pack key, zero otherwise
*/
static int mxf_is_partition_pack_key(UID key)
{
//NOTE: this is a little lax since it doesn't constraint key[14]
return !memcmp(key, mxf_header_partition_pack_key, 13) &&
key[13] >= 2 && key[13] <= 4;
}
/**
* Parses a metadata KLV
* @return <0 on error, 0 otherwise
*/
static int mxf_parse_klv(MXFContext *mxf, KLVPacket klv, MXFMetadataReadFunc *read,
int ctx_size, enum MXFMetadataSetType type)
{
AVFormatContext *s = mxf->fc;
int res;
if (klv.key[5] == 0x53) {
res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type);
} else {
uint64_t next = avio_tell(s->pb) + klv.length;
res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);
/* only seek forward, else this can loop for a long time */
if (avio_tell(s->pb) > next) {
av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",
klv.offset);
return AVERROR_INVALIDDATA;
}
avio_seek(s->pb, next, SEEK_SET);
}
if (res < 0) {
av_log(s, AV_LOG_ERROR, "error reading header metadata\n");
return res;
}
return 0;
}
/**
* Seeks to the previous partition and parses it, if possible
* @return <= 0 if we should stop parsing, > 0 if we should keep going
*/
static int mxf_seek_to_previous_partition(MXFContext *mxf)
{
AVIOContext *pb = mxf->fc->pb;
KLVPacket klv;
int64_t current_partition_ofs;
int ret;
if (!mxf->current_partition ||
mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell)
return 0; /* we've parsed all partitions */
/* seek to previous partition */
current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in
avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET);
mxf->current_partition = NULL;
av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n");
/* Make sure this is actually a PartitionPack, and if so parse it.
* See deadlock2.mxf
*/
if ((ret = klv_read_packet(&klv, pb)) < 0) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n");
return ret;
}
if (!mxf_is_partition_pack_key(klv.key)) {
av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset);
return AVERROR_INVALIDDATA;
}
/* We can't just check ofs >= current_partition_ofs because PreviousPartition
* can point to just before the current partition, causing klv_read_packet()
* to sync back up to it. See deadlock3.mxf
*/
if (klv.offset >= current_partition_ofs) {
av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %"
PRIx64 " indirectly points to itself\n", current_partition_ofs);
return AVERROR_INVALIDDATA;
}
if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0)
return ret;
return 1;
}
/**
* Called when essence is encountered
* @return <= 0 if we should stop parsing, > 0 if we should keep going
*/
static int mxf_parse_handle_essence(MXFContext *mxf)
{
AVIOContext *pb = mxf->fc->pb;
int64_t ret;
if (mxf->parsing_backward) {
return mxf_seek_to_previous_partition(mxf);
} else {
if (!mxf->footer_partition) {
av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n");
return 0;
}
av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n");
/* remember where we were so we don't end up seeking further back than this */
mxf->last_forward_tell = avio_tell(pb);
if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) {
av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n");
return -1;
}
/* seek to FooterPartition and parse backward */
if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) {
av_log(mxf->fc, AV_LOG_ERROR,
"failed to seek to FooterPartition @ 0x%" PRIx64
" (%"PRId64") - partial file?\n",
mxf->run_in + mxf->footer_partition, ret);
return ret;
}
mxf->current_partition = NULL;
mxf->parsing_backward = 1;
}
return 1;
}
/**
* Called when the next partition or EOF is encountered
* @return <= 0 if we should stop parsing, > 0 if we should keep going
*/
static int mxf_parse_handle_partition_or_eof(MXFContext *mxf)
{
return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1;
}
static MXFWrappingScheme mxf_get_wrapping_by_body_sid(AVFormatContext *s, int body_sid)
{
for (int i = 0; i < s->nb_streams; i++) {
MXFTrack *track = s->streams[i]->priv_data;
if (track && track->body_sid == body_sid && track->wrapping != UnknownWrapped)
return track->wrapping;
}
return UnknownWrapped;
}
/**
* Figures out the proper offset and length of the essence container in each partition
*/
static void mxf_compute_essence_containers(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
int x;
for (x = 0; x < mxf->partitions_count; x++) {
MXFPartition *p = &mxf->partitions[x];
MXFWrappingScheme wrapping;
if (!p->body_sid)
continue; /* BodySID == 0 -> no essence */
/* for clip wrapped essences we point essence_offset after the KL (usually klv.offset + 20 or 25)
* otherwise we point essence_offset at the key of the first essence KLV.
*/
wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_by_body_sid(s, p->body_sid);
if (wrapping == ClipWrapped) {
p->essence_offset = p->first_essence_klv.next_klv - p->first_essence_klv.length;
p->essence_length = p->first_essence_klv.length;
} else {
p->essence_offset = p->first_essence_klv.offset;
/* essence container spans to the next partition */
if (x < mxf->partitions_count - 1)
p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset;
if (p->essence_length < 0) {
/* next ThisPartition < essence_offset */
p->essence_length = 0;
av_log(mxf->fc, AV_LOG_ERROR,
"partition %i: bad ThisPartition = %"PRIX64"\n",
x+1, mxf->partitions[x+1].this_partition);
}
}
}
}
static int is_pcm(enum AVCodecID codec_id)
{
/* we only care about "normal" PCM codecs until we get samples */
return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD;
}
static MXFIndexTable *mxf_find_index_table(MXFContext *mxf, int index_sid)
{
int i;
for (i = 0; i < mxf->nb_index_tables; i++)
if (mxf->index_tables[i].index_sid == index_sid)
return &mxf->index_tables[i];
return NULL;
}
/**
* Deal with the case where for some audio atoms EditUnitByteCount is
* very small (2, 4..). In those cases we should read more than one
* sample per call to mxf_read_packet().
*/
static void mxf_compute_edit_units_per_packet(MXFContext *mxf, AVStream *st)
{
MXFTrack *track = st->priv_data;
MXFIndexTable *t;
if (!track)
return;
track->edit_units_per_packet = 1;
if (track->wrapping != ClipWrapped)
return;
t = mxf_find_index_table(mxf, track->index_sid);
/* expect PCM with exactly one index table segment and a small (< 32) EUBC */
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
!is_pcm(st->codecpar->codec_id) ||
!t ||
t->nb_segments != 1 ||
t->segments[0]->edit_unit_byte_count >= 32)
return;
/* arbitrarily default to 48 kHz PAL audio frame size */
/* TODO: We could compute this from the ratio between the audio
* and video edit rates for 48 kHz NTSC we could use the
* 1802-1802-1802-1802-1801 pattern. */
track->edit_units_per_packet = FFMAX(1, track->edit_rate.num / track->edit_rate.den / 25);
}
/**
* Deal with the case where ClipWrapped essences does not have any IndexTableSegments.
*/
static int mxf_handle_missing_index_segment(MXFContext *mxf, AVStream *st)
{
MXFTrack *track = st->priv_data;
MXFIndexTableSegment *segment = NULL;
MXFPartition *p = NULL;
int essence_partition_count = 0;
int edit_unit_byte_count = 0;
int i, ret;
if (!track || track->wrapping != ClipWrapped)
return 0;
/* check if track already has an IndexTableSegment */
for (i = 0; i < mxf->metadata_sets_count; i++) {
if (mxf->metadata_sets[i]->type == IndexTableSegment) {
MXFIndexTableSegment *s = (MXFIndexTableSegment*)mxf->metadata_sets[i];
if (s->body_sid == track->body_sid)
return 0;
}
}
/* find the essence partition */
for (i = 0; i < mxf->partitions_count; i++) {
/* BodySID == 0 -> no essence */
if (mxf->partitions[i].body_sid != track->body_sid)
continue;
p = &mxf->partitions[i];
essence_partition_count++;
}
/* only handle files with a single essence partition */
if (essence_partition_count != 1)
return 0;
if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && is_pcm(st->codecpar->codec_id)) {
edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
} else if (st->duration > 0 && p->first_essence_klv.length > 0 && p->first_essence_klv.length % st->duration == 0) {
edit_unit_byte_count = p->first_essence_klv.length / st->duration;
}
if (edit_unit_byte_count <= 0)
return 0;
av_log(mxf->fc, AV_LOG_WARNING, "guessing index for stream %d using edit unit byte count %d\n", st->index, edit_unit_byte_count);
if (!(segment = av_mallocz(sizeof(*segment))))
return AVERROR(ENOMEM);
if ((ret = mxf_add_metadata_set(mxf, segment))) {
mxf_free_metadataset((MXFMetadataSet**)&segment, 1);
return ret;
}
/* Make sure we have nonzero unique index_sid, body_sid will be ok, because
* using the same SID for index is forbidden in MXF. */
if (!track->index_sid)
track->index_sid = track->body_sid;
segment->type = IndexTableSegment;
/* stream will be treated as small EditUnitByteCount */
segment->edit_unit_byte_count = edit_unit_byte_count;
segment->index_start_position = 0;
segment->index_duration = st->duration;
segment->index_edit_rate = av_inv_q(st->time_base);
segment->index_sid = track->index_sid;
segment->body_sid = p->body_sid;
return 0;
}
static void mxf_read_random_index_pack(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
uint32_t length;
int64_t file_size, max_rip_length, min_rip_length;
KLVPacket klv;
if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL))
return;
file_size = avio_size(s->pb);
/* S377m says to check the RIP length for "silly" values, without defining "silly".
* The limit below assumes a file with nothing but partition packs and a RIP.
* Before changing this, consider that a muxer may place each sample in its own partition.
*
* 105 is the size of the smallest possible PartitionPack
* 12 is the size of each RIP entry
* 28 is the size of the RIP header and footer, assuming an 8-byte BER
*/
max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28;
max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly
/* We're only interested in RIPs with at least two entries.. */
min_rip_length = 16+1+24+4;
/* See S377m section 11 */
avio_seek(s->pb, file_size - 4, SEEK_SET);
length = avio_rb32(s->pb);
if (length < min_rip_length || length > max_rip_length)
goto end;
avio_seek(s->pb, file_size - length, SEEK_SET);
if (klv_read_packet(&klv, s->pb) < 0 ||
!IS_KLV_KEY(klv.key, mxf_random_index_pack_key) ||
klv.length != length - 20)
goto end;
avio_skip(s->pb, klv.length - 12);
mxf->footer_partition = avio_rb64(s->pb);
/* sanity check */
if (mxf->run_in + mxf->footer_partition >= file_size) {
av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n");
mxf->footer_partition = 0;
}
end:
avio_seek(s->pb, mxf->run_in, SEEK_SET);
}
static int mxf_read_header(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
KLVPacket klv;
int64_t essence_offset = 0;
int ret;
mxf->last_forward_tell = INT64_MAX;
if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {
av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");
return AVERROR_INVALIDDATA;
}
avio_seek(s->pb, -14, SEEK_CUR);
mxf->fc = s;
mxf->run_in = avio_tell(s->pb);
mxf_read_random_index_pack(s);
while (!avio_feof(s->pb)) {
const MXFMetadataReadTableEntry *metadata;
if (klv_read_packet(&klv, s->pb) < 0) {
/* EOF - seek to previous partition or stop */
if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
break;
else
continue;
}
PRINT_KEY(s, "read header", klv.key);
av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||
IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_system_item_key_cp) ||
IS_KLV_KEY(klv.key, mxf_system_item_key_gc)) {
if (!mxf->current_partition) {
av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");
return AVERROR_INVALIDDATA;
}
if (!mxf->current_partition->first_essence_klv.offset)
mxf->current_partition->first_essence_klv = klv;
if (!essence_offset)
essence_offset = klv.offset;
/* seek to footer, previous partition or stop */
if (mxf_parse_handle_essence(mxf) <= 0)
break;
continue;
} else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) {
/* next partition pack - keep going, seek to previous partition or stop */
if(mxf_parse_handle_partition_or_eof(mxf) <= 0)
break;
else if (mxf->parsing_backward)
continue;
/* we're still parsing forward. proceed to parsing this partition pack */
}
for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {
if (IS_KLV_KEY(klv.key, metadata->key)) {
if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0)
goto fail;
break;
}
}
if (!metadata->read) {
av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n",
UID_ARG(klv.key));
avio_skip(s->pb, klv.length);
}
}
/* FIXME avoid seek */
if (!essence_offset) {
av_log(s, AV_LOG_ERROR, "no essence\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
avio_seek(s->pb, essence_offset, SEEK_SET);
/* we need to do this before computing the index tables
* to be able to fill in zero IndexDurations with st->duration */
if ((ret = mxf_parse_structural_metadata(mxf)) < 0)
goto fail;
for (int i = 0; i < s->nb_streams; i++)
mxf_handle_missing_index_segment(mxf, s->streams[i]);
if ((ret = mxf_compute_index_tables(mxf)) < 0)
goto fail;
if (mxf->nb_index_tables > 1) {
/* TODO: look up which IndexSID to use via EssenceContainerData */
av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",
mxf->nb_index_tables, mxf->index_tables[0].index_sid);
} else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom && (s->error_recognition & AV_EF_EXPLODE)) {
av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
mxf_compute_essence_containers(s);
for (int i = 0; i < s->nb_streams; i++)
mxf_compute_edit_units_per_packet(mxf, s->streams[i]);
return 0;
fail:
mxf_read_close(s);
return ret;
}
/* Get the edit unit of the next packet from current_offset in a track. The returned edit unit can be original_duration as well! */
static int mxf_get_next_track_edit_unit(MXFContext *mxf, MXFTrack *track, int64_t current_offset, int64_t *edit_unit_out)
{
int64_t a, b, m, offset;
MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
if (!t || track->original_duration <= 0)
return -1;
a = -1;
b = track->original_duration;
while (b - a > 1) {
m = (a + b) >> 1;
if (mxf_edit_unit_absolute_offset(mxf, t, m, track->edit_rate, NULL, &offset, NULL, 0) < 0)
return -1;
if (offset < current_offset)
a = m;
else
b = m;
}
*edit_unit_out = b;
return 0;
}
static int64_t mxf_compute_sample_count(MXFContext *mxf, AVStream *st,
int64_t edit_unit)
{
int i, total = 0, size = 0;
MXFTrack *track = st->priv_data;
AVRational time_base = av_inv_q(track->edit_rate);
AVRational sample_rate = av_inv_q(st->time_base);
const MXFSamplesPerFrame *spf = NULL;
int64_t sample_count;
// For non-audio sample_count equals current edit unit
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
return edit_unit;
if ((sample_rate.num / sample_rate.den) == 48000)
spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base);
if (!spf) {
int remainder = (sample_rate.num * time_base.num) %
(time_base.den * sample_rate.den);
if (remainder)
av_log(mxf->fc, AV_LOG_WARNING,
"seeking detected on stream #%d with time base (%d/%d) and "
"sample rate (%d/%d), audio pts won't be accurate.\n",
st->index, time_base.num, time_base.den,
sample_rate.num, sample_rate.den);
return av_rescale_q(edit_unit, sample_rate, track->edit_rate);
}
while (spf->samples_per_frame[size]) {
total += spf->samples_per_frame[size];
size++;
}
av_assert2(size);
sample_count = (edit_unit / size) * (uint64_t)total;
for (i = 0; i < edit_unit % size; i++) {
sample_count += spf->samples_per_frame[i];
}
return sample_count;
}
/**
* Make sure track->sample_count is correct based on what offset we're currently at.
* Also determine the next edit unit (or packet) offset.
* @return next_ofs if OK, <0 on error
*/
static int64_t mxf_set_current_edit_unit(MXFContext *mxf, AVStream *st, int64_t current_offset, int resync)
{
int64_t next_ofs = -1;
MXFTrack *track = st->priv_data;
int64_t edit_unit = av_rescale_q(track->sample_count, st->time_base, av_inv_q(track->edit_rate));
int64_t new_edit_unit;
MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
if (!t || track->wrapping == UnknownWrapped)
return -1;
if (mxf_edit_unit_absolute_offset(mxf, t, edit_unit + track->edit_units_per_packet, track->edit_rate, NULL, &next_ofs, NULL, 0) < 0 &&
(next_ofs = mxf_essence_container_end(mxf, t->body_sid)) <= 0) {
av_log(mxf->fc, AV_LOG_ERROR, "unable to compute the size of the last packet\n");
return -1;
}
/* check if the next edit unit offset (next_ofs) starts ahead of current_offset */
if (next_ofs > current_offset)
return next_ofs;
if (!resync) {
av_log(mxf->fc, AV_LOG_ERROR, "cannot find current edit unit for stream %d, invalid index?\n", st->index);
return -1;
}
if (mxf_get_next_track_edit_unit(mxf, track, current_offset + 1, &new_edit_unit) < 0 || new_edit_unit <= 0) {
av_log(mxf->fc, AV_LOG_ERROR, "failed to find next track edit unit in stream %d\n", st->index);
return -1;
}
new_edit_unit--;
track->sample_count = mxf_compute_sample_count(mxf, st, new_edit_unit);
av_log(mxf->fc, AV_LOG_WARNING, "edit unit sync lost on stream %d, jumping from %"PRId64" to %"PRId64"\n", st->index, edit_unit, new_edit_unit);
return mxf_set_current_edit_unit(mxf, st, current_offset, 0);
}
static int mxf_set_audio_pts(MXFContext *mxf, AVCodecParameters *par,
AVPacket *pkt)
{
MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data;
int64_t bits_per_sample = par->bits_per_coded_sample;
if (!bits_per_sample)
bits_per_sample = av_get_bits_per_sample(par->codec_id);
pkt->pts = track->sample_count;
if ( par->channels <= 0
|| bits_per_sample <= 0
|| par->channels * (int64_t)bits_per_sample < 8)
return AVERROR(EINVAL);
track->sample_count += pkt->size / (par->channels * (int64_t)bits_per_sample / 8);
return 0;
}
static int mxf_set_pts(MXFContext *mxf, AVStream *st, AVPacket *pkt)
{
AVCodecParameters *par = st->codecpar;
MXFTrack *track = st->priv_data;
if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
/* see if we have an index table to derive timestamps from */
MXFIndexTable *t = mxf_find_index_table(mxf, track->index_sid);
if (t && track->sample_count < t->nb_ptses) {
pkt->dts = track->sample_count + t->first_dts;
pkt->pts = t->ptses[track->sample_count];
} else if (track->intra_only) {
/* intra-only -> PTS = EditUnit.
* let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
pkt->pts = track->sample_count;
}
track->sample_count++;
} else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
int ret = mxf_set_audio_pts(mxf, par, pkt);
if (ret < 0)
return ret;
} else if (track) {
track->sample_count++;
}
return 0;
}
static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt)
{
KLVPacket klv;
MXFContext *mxf = s->priv_data;
int ret;
while (1) {
int64_t max_data_size;
int64_t pos = avio_tell(s->pb);
if (pos < mxf->current_klv_data.next_klv - mxf->current_klv_data.length || pos >= mxf->current_klv_data.next_klv) {
mxf->current_klv_data = (KLVPacket){{0}};
ret = klv_read_packet(&klv, s->pb);
if (ret < 0)
break;
max_data_size = klv.length;
pos = klv.next_klv - klv.length;
PRINT_KEY(s, "read packet", klv.key);
av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
ret = mxf_decrypt_triplet(s, pkt, &klv);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
return ret;
}
return 0;
}
} else {
klv = mxf->current_klv_data;
max_data_size = klv.next_klv - pos;
}
if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
int body_sid = find_body_sid_by_offset(mxf, klv.offset);
int index = mxf_get_stream_index(s, &klv, body_sid);
int64_t next_ofs;
AVStream *st;
MXFTrack *track;
if (index < 0) {
av_log(s, AV_LOG_ERROR,
"error getting stream index %"PRIu32"\n",
AV_RB32(klv.key + 12));
goto skip;
}
st = s->streams[index];
track = st->priv_data;
if (s->streams[index]->discard == AVDISCARD_ALL)
goto skip;
next_ofs = mxf_set_current_edit_unit(mxf, st, pos, 1);
if (track->wrapping != FrameWrapped) {
int64_t size;
if (next_ofs <= 0) {
// If we have no way to packetize the data, then return it in chunks...
if (klv.next_klv - klv.length == pos && max_data_size > MXF_MAX_CHUNK_SIZE) {
st->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_request_sample(s, "Huge KLV without proper index in non-frame wrapped essence");
}
size = FFMIN(max_data_size, MXF_MAX_CHUNK_SIZE);
} else {
if ((size = next_ofs - pos) <= 0) {
av_log(s, AV_LOG_ERROR, "bad size: %"PRId64"\n", size);
ret = AVERROR_INVALIDDATA;
goto skip;
}
// We must not overread, because the next edit unit might be in another KLV
if (size > max_data_size)
size = max_data_size;
}
mxf->current_klv_data = klv;
klv.offset = pos;
klv.length = size;
klv.next_klv = klv.offset + klv.length;
}
/* check for 8 channels AES3 element */
if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
pkt, klv.length);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
mxf->current_klv_data = (KLVPacket){{0}};
return ret;
}
} else {
ret = av_get_packet(s->pb, pkt, klv.length);
if (ret < 0) {
mxf->current_klv_data = (KLVPacket){{0}};
return ret;
}
}
pkt->stream_index = index;
pkt->pos = klv.offset;
ret = mxf_set_pts(mxf, st, pkt);
if (ret < 0) {
mxf->current_klv_data = (KLVPacket){{0}};
return ret;
}
/* seek for truncated packets */
avio_seek(s->pb, klv.next_klv, SEEK_SET);
return 0;
} else {
skip:
avio_skip(s->pb, max_data_size);
mxf->current_klv_data = (KLVPacket){{0}};
}
}
return avio_feof(s->pb) ? AVERROR_EOF : ret;
}
static int mxf_read_close(AVFormatContext *s)
{
MXFContext *mxf = s->priv_data;
int i;
av_freep(&mxf->packages_refs);
av_freep(&mxf->essence_container_data_refs);
for (i = 0; i < s->nb_streams; i++)
s->streams[i]->priv_data = NULL;
for (i = 0; i < mxf->metadata_sets_count; i++) {
mxf_free_metadataset(mxf->metadata_sets + i, 1);
}
av_freep(&mxf->partitions);
av_freep(&mxf->metadata_sets);
av_freep(&mxf->aesc);
av_freep(&mxf->local_tags);
if (mxf->index_tables) {
for (i = 0; i < mxf->nb_index_tables; i++) {
av_freep(&mxf->index_tables[i].segments);
av_freep(&mxf->index_tables[i].ptses);
av_freep(&mxf->index_tables[i].fake_index);
av_freep(&mxf->index_tables[i].offsets);
}
}
av_freep(&mxf->index_tables);
return 0;
}
static int mxf_probe(AVProbeData *p) {
const uint8_t *bufp = p->buf;
const uint8_t *end = p->buf + p->buf_size;
if (p->buf_size < sizeof(mxf_header_partition_pack_key))
return 0;
/* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */
end -= sizeof(mxf_header_partition_pack_key);
for (; bufp < end;) {
if (!((bufp[13] - 1) & 0xF2)){
if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) &&
AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) &&
AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) &&
AV_RN16(bufp+12) == AV_RN16(mxf_header_partition_pack_key+12))
return AVPROBE_SCORE_MAX;
bufp ++;
} else
bufp += 10;
}
return 0;
}
/* rudimentary byte seek */
/* XXX: use MXF Index */
static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
{
AVStream *st = s->streams[stream_index];
int64_t seconds;
MXFContext* mxf = s->priv_data;
int64_t seekpos;
int i, ret;
MXFIndexTable *t;
MXFTrack *source_track = st->priv_data;
if (!source_track)
return 0;
/* if audio then truncate sample_time to EditRate */
if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
sample_time = av_rescale_q(sample_time, st->time_base,
av_inv_q(source_track->edit_rate));
if (mxf->nb_index_tables <= 0) {
if (!s->bit_rate)
return AVERROR_INVALIDDATA;
if (sample_time < 0)
sample_time = 0;
seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den);
seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET);
if (seekpos < 0)
return seekpos;
ff_update_cur_dts(s, st, sample_time);
mxf->current_klv_data = (KLVPacket){{0}};
} else {
MXFPartition *partition;
t = &mxf->index_tables[0];
if (t->index_sid != source_track->index_sid) {
/* If the first index table does not belong to the stream, then find a stream which does belong to the index table */
for (i = 0; i < s->nb_streams; i++) {
MXFTrack *new_source_track = s->streams[i]->priv_data;
if (new_source_track && new_source_track->index_sid == t->index_sid) {
sample_time = av_rescale_q(sample_time, new_source_track->edit_rate, source_track->edit_rate);
source_track = new_source_track;
st = s->streams[i];
break;
}
}
if (i == s->nb_streams)
return AVERROR_INVALIDDATA;
}
/* clamp above zero, else ff_index_search_timestamp() returns negative
* this also means we allow seeking before the start */
sample_time = FFMAX(sample_time, 0);
if (t->fake_index) {
/* The first frames may not be keyframes in presentation order, so
* we have to advance the target to be able to find the first
* keyframe backwards... */
if (!(flags & AVSEEK_FLAG_ANY) &&
(flags & AVSEEK_FLAG_BACKWARD) &&
t->ptses[0] != AV_NOPTS_VALUE &&
sample_time < t->ptses[0] &&
(t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME))
sample_time = t->ptses[0];
/* behave as if we have a proper index */
if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0)
return sample_time;
/* get the stored order index from the display order index */
sample_time += t->offsets[sample_time];
} else {
/* no IndexEntryArray (one or more CBR segments)
* make sure we don't seek past the end */
sample_time = FFMIN(sample_time, source_track->original_duration - 1);
}
if (source_track->wrapping == UnknownWrapped)
av_log(mxf->fc, AV_LOG_WARNING, "attempted seek in an UnknownWrapped essence\n");
if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, source_track->edit_rate, &sample_time, &seekpos, &partition, 1)) < 0)
return ret;
ff_update_cur_dts(s, st, sample_time);
if (source_track->wrapping == ClipWrapped) {
KLVPacket klv = partition->first_essence_klv;
if (seekpos < klv.next_klv - klv.length || seekpos >= klv.next_klv) {
av_log(mxf->fc, AV_LOG_ERROR, "attempted seek out of clip wrapped KLV\n");
return AVERROR_INVALIDDATA;
}
mxf->current_klv_data = klv;
} else {
mxf->current_klv_data = (KLVPacket){{0}};
}
avio_seek(s->pb, seekpos, SEEK_SET);
}
// Update all tracks sample count
for (i = 0; i < s->nb_streams; i++) {
AVStream *cur_st = s->streams[i];
MXFTrack *cur_track = cur_st->priv_data;
if (cur_track) {
int64_t track_edit_unit = sample_time;
if (st != cur_st)
mxf_get_next_track_edit_unit(mxf, cur_track, seekpos, &track_edit_unit);
cur_track->sample_count = mxf_compute_sample_count(mxf, cur_st, track_edit_unit);
}
}
return 0;
}
AVInputFormat ff_mxf_demuxer = {
.name = "mxf",
.long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
.flags = AVFMT_SEEK_TO_PTS,
.priv_data_size = sizeof(MXFContext),
.read_probe = mxf_probe,
.read_header = mxf_read_header,
.read_packet = mxf_read_packet,
.read_close = mxf_read_close,
.read_seek = mxf_read_seek,
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_467_0 |
crossvul-cpp_data_bad_2716_0 | /**
* Copyright (c) 2012
*
* Gregory Detal <gregory.detal@uclouvain.be>
* Christoph Paasch <christoph.paasch@uclouvain.be>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the University nor of the Laboratory may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* \summary: Multipath TCP (MPTCP) printer */
/* specification: RFC 6824 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "tcp.h"
#define MPTCP_SUB_CAPABLE 0x0
#define MPTCP_SUB_JOIN 0x1
#define MPTCP_SUB_DSS 0x2
#define MPTCP_SUB_ADD_ADDR 0x3
#define MPTCP_SUB_REMOVE_ADDR 0x4
#define MPTCP_SUB_PRIO 0x5
#define MPTCP_SUB_FAIL 0x6
#define MPTCP_SUB_FCLOSE 0x7
struct mptcp_option {
uint8_t kind;
uint8_t len;
uint8_t sub_etc; /* subtype upper 4 bits, other stuff lower 4 bits */
};
#define MPTCP_OPT_SUBTYPE(sub_etc) (((sub_etc) >> 4) & 0xF)
struct mp_capable {
uint8_t kind;
uint8_t len;
uint8_t sub_ver;
uint8_t flags;
uint8_t sender_key[8];
uint8_t receiver_key[8];
};
#define MP_CAPABLE_OPT_VERSION(sub_ver) (((sub_ver) >> 0) & 0xF)
#define MP_CAPABLE_C 0x80
#define MP_CAPABLE_S 0x01
struct mp_join {
uint8_t kind;
uint8_t len;
uint8_t sub_b;
uint8_t addr_id;
union {
struct {
uint8_t token[4];
uint8_t nonce[4];
} syn;
struct {
uint8_t mac[8];
uint8_t nonce[4];
} synack;
struct {
uint8_t mac[20];
} ack;
} u;
};
#define MP_JOIN_B 0x01
struct mp_dss {
uint8_t kind;
uint8_t len;
uint8_t sub;
uint8_t flags;
};
#define MP_DSS_F 0x10
#define MP_DSS_m 0x08
#define MP_DSS_M 0x04
#define MP_DSS_a 0x02
#define MP_DSS_A 0x01
struct mp_add_addr {
uint8_t kind;
uint8_t len;
uint8_t sub_ipver;
uint8_t addr_id;
union {
struct {
uint8_t addr[4];
uint8_t port[2];
} v4;
struct {
uint8_t addr[16];
uint8_t port[2];
} v6;
} u;
};
#define MP_ADD_ADDR_IPVER(sub_ipver) (((sub_ipver) >> 0) & 0xF)
struct mp_remove_addr {
uint8_t kind;
uint8_t len;
uint8_t sub;
/* list of addr_id */
uint8_t addrs_id;
};
struct mp_fail {
uint8_t kind;
uint8_t len;
uint8_t sub;
uint8_t resv;
uint8_t data_seq[8];
};
struct mp_close {
uint8_t kind;
uint8_t len;
uint8_t sub;
uint8_t rsv;
uint8_t key[8];
};
struct mp_prio {
uint8_t kind;
uint8_t len;
uint8_t sub_b;
uint8_t addr_id;
};
#define MP_PRIO_B 0x01
static int
dummy_print(netdissect_options *ndo _U_,
const u_char *opt _U_, u_int opt_len _U_, u_char flags _U_)
{
return 1;
}
static int
mp_capable_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_capable *mpc = (const struct mp_capable *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK))
return 0;
if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) {
ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver)));
return 1;
}
if (mpc->flags & MP_CAPABLE_C)
ND_PRINT((ndo, " csum"));
ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key)));
if (opt_len == 20) /* ACK */
ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key)));
ND_PRINT((ndo, "}"));
return 1;
}
static int
mp_join_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_join *mpj = (const struct mp_join *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) &&
!(opt_len == 24 && flags & TH_ACK))
return 0;
if (opt_len != 24) {
if (mpj->sub_b & MP_JOIN_B)
ND_PRINT((ndo, " backup"));
ND_PRINT((ndo, " id %u", mpj->addr_id));
}
switch (opt_len) {
case 12: /* SYN */
ND_PRINT((ndo, " token 0x%x" " nonce 0x%x",
EXTRACT_32BITS(mpj->u.syn.token),
EXTRACT_32BITS(mpj->u.syn.nonce)));
break;
case 16: /* SYN/ACK */
ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x",
EXTRACT_64BITS(mpj->u.synack.mac),
EXTRACT_32BITS(mpj->u.synack.nonce)));
break;
case 24: {/* ACK */
size_t i;
ND_PRINT((ndo, " hmac 0x"));
for (i = 0; i < sizeof(mpj->u.ack.mac); ++i)
ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i]));
}
default:
break;
}
return 1;
}
static u_int mp_dss_len(const struct mp_dss *m, int csum)
{
u_int len;
len = 4;
if (m->flags & MP_DSS_A) {
/* Ack present - 4 or 8 octets */
len += (m->flags & MP_DSS_a) ? 8 : 4;
}
if (m->flags & MP_DSS_M) {
/*
* Data Sequence Number (DSN), Subflow Sequence Number (SSN),
* Data-Level Length present, and Checksum possibly present.
* All but the Checksum are 10 bytes if the m flag is
* clear (4-byte DSN) and 14 bytes if the m flag is set
* (8-byte DSN).
*/
len += (m->flags & MP_DSS_m) ? 14 : 10;
/*
* The Checksum is present only if negotiated.
*/
if (csum)
len += 2;
}
return len;
}
static int
mp_dss_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_dss *mdss = (const struct mp_dss *) opt;
if ((opt_len != mp_dss_len(mdss, 1) &&
opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN)
return 0;
if (mdss->flags & MP_DSS_F)
ND_PRINT((ndo, " fin"));
opt += 4;
if (mdss->flags & MP_DSS_A) {
ND_PRINT((ndo, " ack "));
if (mdss->flags & MP_DSS_a) {
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
} else {
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
}
}
if (mdss->flags & MP_DSS_M) {
ND_PRINT((ndo, " seq "));
if (mdss->flags & MP_DSS_m) {
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
} else {
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
}
ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt)));
opt += 4;
ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt)));
opt += 2;
if (opt_len == mp_dss_len(mdss, 1))
ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt)));
}
return 1;
}
static int
add_addr_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags _U_)
{
const struct mp_add_addr *add_addr = (const struct mp_add_addr *) opt;
u_int ipver = MP_ADD_ADDR_IPVER(add_addr->sub_ipver);
if (!((opt_len == 8 || opt_len == 10) && ipver == 4) &&
!((opt_len == 20 || opt_len == 22) && ipver == 6))
return 0;
ND_PRINT((ndo, " id %u", add_addr->addr_id));
switch (ipver) {
case 4:
ND_PRINT((ndo, " %s", ipaddr_string(ndo, add_addr->u.v4.addr)));
if (opt_len == 10)
ND_PRINT((ndo, ":%u", EXTRACT_16BITS(add_addr->u.v4.port)));
break;
case 6:
ND_PRINT((ndo, " %s", ip6addr_string(ndo, add_addr->u.v6.addr)));
if (opt_len == 22)
ND_PRINT((ndo, ":%u", EXTRACT_16BITS(add_addr->u.v6.port)));
break;
default:
return 0;
}
return 1;
}
static int
remove_addr_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags _U_)
{
const struct mp_remove_addr *remove_addr = (const struct mp_remove_addr *) opt;
const uint8_t *addr_id = &remove_addr->addrs_id;
if (opt_len < 4)
return 0;
opt_len -= 3;
ND_PRINT((ndo, " id"));
while (opt_len--)
ND_PRINT((ndo, " %u", *addr_id++));
return 1;
}
static int
mp_prio_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags _U_)
{
const struct mp_prio *mpp = (const struct mp_prio *) opt;
if (opt_len != 3 && opt_len != 4)
return 0;
if (mpp->sub_b & MP_PRIO_B)
ND_PRINT((ndo, " backup"));
else
ND_PRINT((ndo, " non-backup"));
if (opt_len == 4)
ND_PRINT((ndo, " id %u", mpp->addr_id));
return 1;
}
static int
mp_fail_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags _U_)
{
if (opt_len != 12)
return 0;
ND_PRINT((ndo, " seq %" PRIu64, EXTRACT_64BITS(opt + 4)));
return 1;
}
static int
mp_fast_close_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags _U_)
{
if (opt_len != 12)
return 0;
ND_PRINT((ndo, " key 0x%" PRIx64, EXTRACT_64BITS(opt + 4)));
return 1;
}
static const struct {
const char *name;
int (*print)(netdissect_options *, const u_char *, u_int, u_char);
} mptcp_options[] = {
{ "capable", mp_capable_print},
{ "join", mp_join_print },
{ "dss", mp_dss_print },
{ "add-addr", add_addr_print },
{ "rem-addr", remove_addr_print },
{ "prio", mp_prio_print },
{ "fail", mp_fail_print },
{ "fast-close", mp_fast_close_print },
{ "unknown", dummy_print },
};
int
mptcp_print(netdissect_options *ndo,
const u_char *cp, u_int len, u_char flags)
{
const struct mptcp_option *opt;
u_int subtype;
if (len < 3)
return 0;
opt = (const struct mptcp_option *) cp;
subtype = min(MPTCP_OPT_SUBTYPE(opt->sub_etc), MPTCP_SUB_FCLOSE + 1);
ND_PRINT((ndo, " %s", mptcp_options[subtype].name));
return mptcp_options[subtype].print(ndo, cp, len, flags);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2716_0 |
crossvul-cpp_data_good_701_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>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) > end - len )
{
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
*/
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/good_701_0 |
crossvul-cpp_data_bad_331_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"
static const char tstr[] = "[|BGP]";
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_TCHECK_8BITS(opt + i + cap_offset + 3);
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, "%s", tstr));
}
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, "%s", tstr));
}
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, "%s", tstr));
}
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, "%s", tstr));
}
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, "%s", tstr));
}
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, "%s", tstr));
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, " %s", tstr));
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, "%s", tstr));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_331_0 |
crossvul-cpp_data_good_2698_0 | /*
* 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_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/good_2698_0 |
crossvul-cpp_data_bad_220_0 | /*
* VC-1 and WMV3 decoder
* Copyright (c) 2011 Mashiat Sarker Shakkhar
* Copyright (c) 2006-2007 Konstantin Shishkov
* Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* VC-1 and WMV3 block decoding routines
*/
#include "avcodec.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "msmpeg4data.h"
#include "unary.h"
#include "vc1.h"
#include "vc1_pred.h"
#include "vc1acdata.h"
#include "vc1data.h"
#define MB_INTRA_VLC_BITS 9
#define DC_VLC_BITS 9
// offset tables for interlaced picture MVDATA decoding
static const uint8_t offset_table[2][9] = {
{ 0, 1, 2, 4, 8, 16, 32, 64, 128 },
{ 0, 1, 3, 7, 15, 31, 63, 127, 255 },
};
// mapping table for internal block representation
static const int block_map[6] = {0, 2, 1, 3, 4, 5};
/***********************************************************************/
/**
* @name VC-1 Bitplane decoding
* @see 8.7, p56
* @{
*/
static inline void init_block_index(VC1Context *v)
{
MpegEncContext *s = &v->s;
ff_init_block_index(s);
if (v->field_mode && !(v->second_field ^ v->tff)) {
s->dest[0] += s->current_picture_ptr->f->linesize[0];
s->dest[1] += s->current_picture_ptr->f->linesize[1];
s->dest[2] += s->current_picture_ptr->f->linesize[2];
}
}
/** @} */ //Bitplane group
static void vc1_put_blocks_clamped(VC1Context *v, int put_signed)
{
MpegEncContext *s = &v->s;
uint8_t *dest;
int block_count = CONFIG_GRAY && (s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 4 : 6;
int fieldtx = 0;
int i;
/* The put pixels loop is one MB row and one MB column behind the decoding
* loop because we can only put pixels when overlap filtering is done. For
* interlaced frame pictures, however, the put pixels loop is only one
* column behind the decoding loop as interlaced frame pictures only need
* horizontal overlap filtering. */
if (!s->first_slice_line && v->fcm != ILACE_FRAME) {
if (s->mb_x) {
for (i = 0; i < block_count; i++) {
if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i] - 1] :
v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i] - 2]) {
dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + ((i & 1) - 2) * 8;
if (put_signed)
s->idsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest,
i > 3 ? s->uvlinesize : s->linesize);
else
s->idsp.put_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest,
i > 3 ? s->uvlinesize : s->linesize);
}
}
}
if (s->mb_x == v->end_mb_x - 1) {
for (i = 0; i < block_count; i++) {
if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i]] :
v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i]]) {
dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + (i & 1) * 8;
if (put_signed)
s->idsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest,
i > 3 ? s->uvlinesize : s->linesize);
else
s->idsp.put_pixels_clamped(v->block[v->top_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest,
i > 3 ? s->uvlinesize : s->linesize);
}
}
}
}
if (s->mb_y == s->end_mb_y - 1 || v->fcm == ILACE_FRAME) {
if (s->mb_x) {
if (v->fcm == ILACE_FRAME)
fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x - 1];
for (i = 0; i < block_count; i++) {
if (i > 3 ? v->mb_type[0][s->block_index[i] - 1] :
v->mb_type[0][s->block_index[i] - 2]) {
if (fieldtx)
dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + ((i & 1) - 2) * 8;
else
dest = s->dest[0] + (i & 2) * 4 * s->linesize + ((i & 1) - 2) * 8;
if (put_signed)
s->idsp.put_signed_pixels_clamped(v->block[v->left_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] - 8 : dest,
i > 3 ? s->uvlinesize : s->linesize << fieldtx);
else
s->idsp.put_pixels_clamped(v->block[v->left_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] - 8 : dest,
i > 3 ? s->uvlinesize : s->linesize << fieldtx);
}
}
}
if (s->mb_x == v->end_mb_x - 1) {
if (v->fcm == ILACE_FRAME)
fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x];
for (i = 0; i < block_count; i++) {
if (v->mb_type[0][s->block_index[i]]) {
if (fieldtx)
dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + (i & 1) * 8;
else
dest = s->dest[0] + (i & 2) * 4 * s->linesize + (i & 1) * 8;
if (put_signed)
s->idsp.put_signed_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] : dest,
i > 3 ? s->uvlinesize : s->linesize << fieldtx);
else
s->idsp.put_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]],
i > 3 ? s->dest[i - 3] : dest,
i > 3 ? s->uvlinesize : s->linesize << fieldtx);
}
}
}
}
}
#define inc_blk_idx(idx) do { \
idx++; \
if (idx >= v->n_allocated_blks) \
idx = 0; \
} while (0)
/***********************************************************************/
/**
* @name VC-1 Block-level functions
* @see 7.1.4, p91 and 8.1.1.7, p(1)04
* @{
*/
/**
* @def GET_MQUANT
* @brief Get macroblock-level quantizer scale
*/
#define GET_MQUANT() \
if (v->dquantfrm) { \
int edges = 0; \
if (v->dqprofile == DQPROFILE_ALL_MBS) { \
if (v->dqbilevel) { \
mquant = (get_bits1(gb)) ? -v->altpq : v->pq; \
} else { \
mqdiff = get_bits(gb, 3); \
if (mqdiff != 7) \
mquant = -v->pq - mqdiff; \
else \
mquant = -get_bits(gb, 5); \
} \
} \
if (v->dqprofile == DQPROFILE_SINGLE_EDGE) \
edges = 1 << v->dqsbedge; \
else if (v->dqprofile == DQPROFILE_DOUBLE_EDGES) \
edges = (3 << v->dqsbedge) % 15; \
else if (v->dqprofile == DQPROFILE_FOUR_EDGES) \
edges = 15; \
if ((edges&1) && !s->mb_x) \
mquant = -v->altpq; \
if ((edges&2) && !s->mb_y) \
mquant = -v->altpq; \
if ((edges&4) && s->mb_x == (s->mb_width - 1)) \
mquant = -v->altpq; \
if ((edges&8) && \
s->mb_y == ((s->mb_height >> v->field_mode) - 1)) \
mquant = -v->altpq; \
if (!mquant || mquant > 31) { \
av_log(v->s.avctx, AV_LOG_ERROR, \
"Overriding invalid mquant %d\n", mquant); \
mquant = 1; \
} \
}
/**
* @def GET_MVDATA(_dmv_x, _dmv_y)
* @brief Get MV differentials
* @see MVDATA decoding from 8.3.5.2, p(1)20
* @param _dmv_x Horizontal differential for decoded MV
* @param _dmv_y Vertical differential for decoded MV
*/
#define GET_MVDATA(_dmv_x, _dmv_y) \
index = 1 + get_vlc2(gb, ff_vc1_mv_diff_vlc[s->mv_table_index].table, \
VC1_MV_DIFF_VLC_BITS, 2); \
if (index > 36) { \
mb_has_coeffs = 1; \
index -= 37; \
} else \
mb_has_coeffs = 0; \
s->mb_intra = 0; \
if (!index) { \
_dmv_x = _dmv_y = 0; \
} else if (index == 35) { \
_dmv_x = get_bits(gb, v->k_x - 1 + s->quarter_sample); \
_dmv_y = get_bits(gb, v->k_y - 1 + s->quarter_sample); \
} else if (index == 36) { \
_dmv_x = 0; \
_dmv_y = 0; \
s->mb_intra = 1; \
} else { \
index1 = index % 6; \
_dmv_x = offset_table[1][index1]; \
val = size_table[index1] - (!s->quarter_sample && index1 == 5); \
if (val > 0) { \
val = get_bits(gb, val); \
sign = 0 - (val & 1); \
_dmv_x = (sign ^ ((val >> 1) + _dmv_x)) - sign; \
} \
\
index1 = index / 6; \
_dmv_y = offset_table[1][index1]; \
val = size_table[index1] - (!s->quarter_sample && index1 == 5); \
if (val > 0) { \
val = get_bits(gb, val); \
sign = 0 - (val & 1); \
_dmv_y = (sign ^ ((val >> 1) + _dmv_y)) - sign; \
} \
}
static av_always_inline void get_mvdata_interlaced(VC1Context *v, int *dmv_x,
int *dmv_y, int *pred_flag)
{
int index, index1;
int extend_x, extend_y;
GetBitContext *gb = &v->s.gb;
int bits, esc;
int val, sign;
if (v->numref) {
bits = VC1_2REF_MVDATA_VLC_BITS;
esc = 125;
} else {
bits = VC1_1REF_MVDATA_VLC_BITS;
esc = 71;
}
extend_x = v->dmvrange & 1;
extend_y = (v->dmvrange >> 1) & 1;
index = get_vlc2(gb, v->imv_vlc->table, bits, 3);
if (index == esc) {
*dmv_x = get_bits(gb, v->k_x);
*dmv_y = get_bits(gb, v->k_y);
if (v->numref) {
if (pred_flag)
*pred_flag = *dmv_y & 1;
*dmv_y = (*dmv_y + (*dmv_y & 1)) >> 1;
}
}
else {
av_assert0(index < esc);
index1 = (index + 1) % 9;
if (index1 != 0) {
val = get_bits(gb, index1 + extend_x);
sign = 0 - (val & 1);
*dmv_x = (sign ^ ((val >> 1) + offset_table[extend_x][index1])) - sign;
} else
*dmv_x = 0;
index1 = (index + 1) / 9;
if (index1 > v->numref) {
val = get_bits(gb, (index1 >> v->numref) + extend_y);
sign = 0 - (val & 1);
*dmv_y = (sign ^ ((val >> 1) + offset_table[extend_y][index1 >> v->numref])) - sign;
} else
*dmv_y = 0;
if (v->numref && pred_flag)
*pred_flag = index1 & 1;
}
}
/** Reconstruct motion vector for B-frame and do motion compensation
*/
static inline void vc1_b_mc(VC1Context *v, int dmv_x[2], int dmv_y[2],
int direct, int mode)
{
if (direct) {
ff_vc1_mc_1mv(v, 0);
ff_vc1_interp_mc(v);
return;
}
if (mode == BMV_TYPE_INTERPOLATED) {
ff_vc1_mc_1mv(v, 0);
ff_vc1_interp_mc(v);
return;
}
ff_vc1_mc_1mv(v, (mode == BMV_TYPE_BACKWARD));
}
/** Get predicted DC value for I-frames only
* prediction dir: left=0, top=1
* @param s MpegEncContext
* @param overlap flag indicating that overlap filtering is used
* @param pq integer part of picture quantizer
* @param[in] n block index in the current MB
* @param dc_val_ptr Pointer to DC predictor
* @param dir_ptr Prediction direction for use in AC prediction
*/
static inline int vc1_i_pred_dc(MpegEncContext *s, int overlap, int pq, int n,
int16_t **dc_val_ptr, int *dir_ptr)
{
int a, b, c, wrap, pred, scale;
int16_t *dc_val;
static const uint16_t dcpred[32] = {
-1, 1024, 512, 341, 256, 205, 171, 146, 128,
114, 102, 93, 85, 79, 73, 68, 64,
60, 57, 54, 51, 49, 47, 45, 43,
41, 39, 38, 37, 35, 34, 33
};
/* find prediction - wmv3_dc_scale always used here in fact */
if (n < 4) scale = s->y_dc_scale;
else scale = s->c_dc_scale;
wrap = s->block_wrap[n];
dc_val = s->dc_val[0] + s->block_index[n];
/* B A
* C X
*/
c = dc_val[ - 1];
b = dc_val[ - 1 - wrap];
a = dc_val[ - wrap];
if (pq < 9 || !overlap) {
/* Set outer values */
if (s->first_slice_line && (n != 2 && n != 3))
b = a = dcpred[scale];
if (s->mb_x == 0 && (n != 1 && n != 3))
b = c = dcpred[scale];
} else {
/* Set outer values */
if (s->first_slice_line && (n != 2 && n != 3))
b = a = 0;
if (s->mb_x == 0 && (n != 1 && n != 3))
b = c = 0;
}
if (abs(a - b) <= abs(b - c)) {
pred = c;
*dir_ptr = 1; // left
} else {
pred = a;
*dir_ptr = 0; // top
}
/* update predictor */
*dc_val_ptr = &dc_val[0];
return pred;
}
/** Get predicted DC value
* prediction dir: left=0, top=1
* @param s MpegEncContext
* @param overlap flag indicating that overlap filtering is used
* @param pq integer part of picture quantizer
* @param[in] n block index in the current MB
* @param a_avail flag indicating top block availability
* @param c_avail flag indicating left block availability
* @param dc_val_ptr Pointer to DC predictor
* @param dir_ptr Prediction direction for use in AC prediction
*/
static inline int ff_vc1_pred_dc(MpegEncContext *s, int overlap, int pq, int n,
int a_avail, int c_avail,
int16_t **dc_val_ptr, int *dir_ptr)
{
int a, b, c, wrap, pred;
int16_t *dc_val;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int q1, q2 = 0;
int dqscale_index;
/* scale predictors if needed */
q1 = FFABS(s->current_picture.qscale_table[mb_pos]);
dqscale_index = s->y_dc_scale_table[q1] - 1;
if (dqscale_index < 0)
return 0;
wrap = s->block_wrap[n];
dc_val = s->dc_val[0] + s->block_index[n];
/* B A
* C X
*/
c = dc_val[ - 1];
b = dc_val[ - 1 - wrap];
a = dc_val[ - wrap];
if (c_avail && (n != 1 && n != 3)) {
q2 = FFABS(s->current_picture.qscale_table[mb_pos - 1]);
if (q2 && q2 != q1)
c = (c * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
}
if (a_avail && (n != 2 && n != 3)) {
q2 = FFABS(s->current_picture.qscale_table[mb_pos - s->mb_stride]);
if (q2 && q2 != q1)
a = (a * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
}
if (a_avail && c_avail && (n != 3)) {
int off = mb_pos;
if (n != 1)
off--;
if (n != 2)
off -= s->mb_stride;
q2 = FFABS(s->current_picture.qscale_table[off]);
if (q2 && q2 != q1)
b = (b * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
}
if (c_avail && (!a_avail || abs(a - b) <= abs(b - c))) {
pred = c;
*dir_ptr = 1; // left
} else if (a_avail) {
pred = a;
*dir_ptr = 0; // top
} else {
pred = 0;
*dir_ptr = 1; // left
}
/* update predictor */
*dc_val_ptr = &dc_val[0];
return pred;
}
/** @} */ // Block group
/**
* @name VC1 Macroblock-level functions in Simple/Main Profiles
* @see 7.1.4, p91 and 8.1.1.7, p(1)04
* @{
*/
static inline int vc1_coded_block_pred(MpegEncContext * s, int n,
uint8_t **coded_block_ptr)
{
int xy, wrap, pred, a, b, c;
xy = s->block_index[n];
wrap = s->b8_stride;
/* B C
* A X
*/
a = s->coded_block[xy - 1 ];
b = s->coded_block[xy - 1 - wrap];
c = s->coded_block[xy - wrap];
if (b == c) {
pred = a;
} else {
pred = c;
}
/* store value */
*coded_block_ptr = &s->coded_block[xy];
return pred;
}
/**
* Decode one AC coefficient
* @param v The VC1 context
* @param last Last coefficient
* @param skip How much zero coefficients to skip
* @param value Decoded AC coefficient value
* @param codingset set of VLC to decode data
* @see 8.1.3.4
*/
static void vc1_decode_ac_coeff(VC1Context *v, int *last, int *skip,
int *value, int codingset)
{
GetBitContext *gb = &v->s.gb;
int index, run, level, lst, sign;
index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3);
if (index != ff_vc1_ac_sizes[codingset] - 1) {
run = vc1_index_decode_table[codingset][index][0];
level = vc1_index_decode_table[codingset][index][1];
lst = index >= vc1_last_decode_table[codingset] || get_bits_left(gb) < 0;
sign = get_bits1(gb);
} else {
int escape = decode210(gb);
if (escape != 2) {
index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3);
run = vc1_index_decode_table[codingset][index][0];
level = vc1_index_decode_table[codingset][index][1];
lst = index >= vc1_last_decode_table[codingset];
if (escape == 0) {
if (lst)
level += vc1_last_delta_level_table[codingset][run];
else
level += vc1_delta_level_table[codingset][run];
} else {
if (lst)
run += vc1_last_delta_run_table[codingset][level] + 1;
else
run += vc1_delta_run_table[codingset][level] + 1;
}
sign = get_bits1(gb);
} else {
lst = get_bits1(gb);
if (v->s.esc3_level_length == 0) {
if (v->pq < 8 || v->dquantfrm) { // table 59
v->s.esc3_level_length = get_bits(gb, 3);
if (!v->s.esc3_level_length)
v->s.esc3_level_length = get_bits(gb, 2) + 8;
} else { // table 60
v->s.esc3_level_length = get_unary(gb, 1, 6) + 2;
}
v->s.esc3_run_length = 3 + get_bits(gb, 2);
}
run = get_bits(gb, v->s.esc3_run_length);
sign = get_bits1(gb);
level = get_bits(gb, v->s.esc3_level_length);
}
}
*last = lst;
*skip = run;
*value = (level ^ -sign) + sign;
}
/** Decode intra block in intra frames - should be faster than decode_intra_block
* @param v VC1Context
* @param block block to decode
* @param[in] n subblock index
* @param coded are AC coeffs present or not
* @param codingset set of VLC to decode data
*/
static int vc1_decode_i_block(VC1Context *v, int16_t block[64], int n,
int coded, int codingset)
{
GetBitContext *gb = &v->s.gb;
MpegEncContext *s = &v->s;
int dc_pred_dir = 0; /* Direction of the DC prediction used */
int i;
int16_t *dc_val;
int16_t *ac_val, *ac_val2;
int dcdiff, scale;
/* Get DC differential */
if (n < 4) {
dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
} else {
dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
}
if (dcdiff < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");
return -1;
}
if (dcdiff) {
const int m = (v->pq == 1 || v->pq == 2) ? 3 - v->pq : 0;
if (dcdiff == 119 /* ESC index value */) {
dcdiff = get_bits(gb, 8 + m);
} else {
if (m)
dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1);
}
if (get_bits1(gb))
dcdiff = -dcdiff;
}
/* Prediction */
dcdiff += vc1_i_pred_dc(&v->s, v->overlap, v->pq, n, &dc_val, &dc_pred_dir);
*dc_val = dcdiff;
/* Store the quantized DC coeff, used for prediction */
if (n < 4)
scale = s->y_dc_scale;
else
scale = s->c_dc_scale;
block[0] = dcdiff * scale;
ac_val = s->ac_val[0][s->block_index[n]];
ac_val2 = ac_val;
if (dc_pred_dir) // left
ac_val -= 16;
else // top
ac_val -= 16 * s->block_wrap[n];
scale = v->pq * 2 + v->halfpq;
//AC Decoding
i = !!coded;
if (coded) {
int last = 0, skip, value;
const uint8_t *zz_table;
int k;
if (v->s.ac_pred) {
if (!dc_pred_dir)
zz_table = v->zz_8x8[2];
else
zz_table = v->zz_8x8[3];
} else
zz_table = v->zz_8x8[1];
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
i += skip;
if (i > 63)
break;
block[zz_table[i++]] = value;
}
/* apply AC prediction if needed */
if (s->ac_pred) {
int sh;
if (dc_pred_dir) { // left
sh = v->left_blk_sh;
} else { // top
sh = v->top_blk_sh;
ac_val += 8;
}
for (k = 1; k < 8; k++)
block[k << sh] += ac_val[k];
}
/* save AC coeffs for further prediction */
for (k = 1; k < 8; k++) {
ac_val2[k] = block[k << v->left_blk_sh];
ac_val2[k + 8] = block[k << v->top_blk_sh];
}
/* scale AC coeffs */
for (k = 1; k < 64; k++)
if (block[k]) {
block[k] *= scale;
if (!v->pquantizer)
block[k] += (block[k] < 0) ? -v->pq : v->pq;
}
} else {
int k;
memset(ac_val2, 0, 16 * 2);
/* apply AC prediction if needed */
if (s->ac_pred) {
int sh;
if (dc_pred_dir) { //left
sh = v->left_blk_sh;
} else { // top
sh = v->top_blk_sh;
ac_val += 8;
ac_val2 += 8;
}
memcpy(ac_val2, ac_val, 8 * 2);
for (k = 1; k < 8; k++) {
block[k << sh] = ac_val[k] * scale;
if (!v->pquantizer && block[k << sh])
block[k << sh] += (block[k << sh] < 0) ? -v->pq : v->pq;
}
}
}
if (s->ac_pred) i = 63;
s->block_last_index[n] = i;
return 0;
}
/** Decode intra block in intra frames - should be faster than decode_intra_block
* @param v VC1Context
* @param block block to decode
* @param[in] n subblock number
* @param coded are AC coeffs present or not
* @param codingset set of VLC to decode data
* @param mquant quantizer value for this macroblock
*/
static int vc1_decode_i_block_adv(VC1Context *v, int16_t block[64], int n,
int coded, int codingset, int mquant)
{
GetBitContext *gb = &v->s.gb;
MpegEncContext *s = &v->s;
int dc_pred_dir = 0; /* Direction of the DC prediction used */
int i;
int16_t *dc_val = NULL;
int16_t *ac_val, *ac_val2;
int dcdiff;
int a_avail = v->a_avail, c_avail = v->c_avail;
int use_pred = s->ac_pred;
int scale;
int q1, q2 = 0;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int quant = FFABS(mquant);
/* Get DC differential */
if (n < 4) {
dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
} else {
dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
}
if (dcdiff < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");
return -1;
}
if (dcdiff) {
const int m = (quant == 1 || quant == 2) ? 3 - quant : 0;
if (dcdiff == 119 /* ESC index value */) {
dcdiff = get_bits(gb, 8 + m);
} else {
if (m)
dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1);
}
if (get_bits1(gb))
dcdiff = -dcdiff;
}
/* Prediction */
dcdiff += ff_vc1_pred_dc(&v->s, v->overlap, quant, n, v->a_avail, v->c_avail, &dc_val, &dc_pred_dir);
*dc_val = dcdiff;
/* Store the quantized DC coeff, used for prediction */
if (n < 4)
scale = s->y_dc_scale;
else
scale = s->c_dc_scale;
block[0] = dcdiff * scale;
/* check if AC is needed at all */
if (!a_avail && !c_avail)
use_pred = 0;
scale = quant * 2 + ((mquant < 0) ? 0 : v->halfpq);
ac_val = s->ac_val[0][s->block_index[n]];
ac_val2 = ac_val;
if (dc_pred_dir) // left
ac_val -= 16;
else // top
ac_val -= 16 * s->block_wrap[n];
q1 = s->current_picture.qscale_table[mb_pos];
if (n == 3)
q2 = q1;
else if (dc_pred_dir) {
if (n == 1)
q2 = q1;
else if (c_avail && mb_pos)
q2 = s->current_picture.qscale_table[mb_pos - 1];
} else {
if (n == 2)
q2 = q1;
else if (a_avail && mb_pos >= s->mb_stride)
q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride];
}
//AC Decoding
i = 1;
if (coded) {
int last = 0, skip, value;
const uint8_t *zz_table;
int k;
if (v->s.ac_pred) {
if (!use_pred && v->fcm == ILACE_FRAME) {
zz_table = v->zzi_8x8;
} else {
if (!dc_pred_dir) // top
zz_table = v->zz_8x8[2];
else // left
zz_table = v->zz_8x8[3];
}
} else {
if (v->fcm != ILACE_FRAME)
zz_table = v->zz_8x8[1];
else
zz_table = v->zzi_8x8;
}
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
i += skip;
if (i > 63)
break;
block[zz_table[i++]] = value;
}
/* apply AC prediction if needed */
if (use_pred) {
int sh;
if (dc_pred_dir) { // left
sh = v->left_blk_sh;
} else { // top
sh = v->top_blk_sh;
ac_val += 8;
}
/* scale predictors if needed*/
q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1;
if (q1 < 1)
return AVERROR_INVALIDDATA;
if (q2)
q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1;
if (q2 && q1 != q2) {
for (k = 1; k < 8; k++)
block[k << sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
} else {
for (k = 1; k < 8; k++)
block[k << sh] += ac_val[k];
}
}
/* save AC coeffs for further prediction */
for (k = 1; k < 8; k++) {
ac_val2[k ] = block[k << v->left_blk_sh];
ac_val2[k + 8] = block[k << v->top_blk_sh];
}
/* scale AC coeffs */
for (k = 1; k < 64; k++)
if (block[k]) {
block[k] *= scale;
if (!v->pquantizer)
block[k] += (block[k] < 0) ? -quant : quant;
}
} else { // no AC coeffs
int k;
memset(ac_val2, 0, 16 * 2);
/* apply AC prediction if needed */
if (use_pred) {
int sh;
if (dc_pred_dir) { // left
sh = v->left_blk_sh;
} else { // top
sh = v->top_blk_sh;
ac_val += 8;
ac_val2 += 8;
}
memcpy(ac_val2, ac_val, 8 * 2);
q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1;
if (q1 < 1)
return AVERROR_INVALIDDATA;
if (q2)
q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1;
if (q2 && q1 != q2) {
for (k = 1; k < 8; k++)
ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
}
for (k = 1; k < 8; k++) {
block[k << sh] = ac_val2[k] * scale;
if (!v->pquantizer && block[k << sh])
block[k << sh] += (block[k << sh] < 0) ? -quant : quant;
}
}
}
if (use_pred) i = 63;
s->block_last_index[n] = i;
return 0;
}
/** Decode intra block in inter frames - more generic version than vc1_decode_i_block
* @param v VC1Context
* @param block block to decode
* @param[in] n subblock index
* @param coded are AC coeffs present or not
* @param mquant block quantizer
* @param codingset set of VLC to decode data
*/
static int vc1_decode_intra_block(VC1Context *v, int16_t block[64], int n,
int coded, int mquant, int codingset)
{
GetBitContext *gb = &v->s.gb;
MpegEncContext *s = &v->s;
int dc_pred_dir = 0; /* Direction of the DC prediction used */
int i;
int16_t *dc_val = NULL;
int16_t *ac_val, *ac_val2;
int dcdiff;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int a_avail = v->a_avail, c_avail = v->c_avail;
int use_pred = s->ac_pred;
int scale;
int q1, q2 = 0;
int quant = FFABS(mquant);
s->bdsp.clear_block(block);
/* XXX: Guard against dumb values of mquant */
quant = av_clip_uintp2(quant, 5);
/* Set DC scale - y and c use the same */
s->y_dc_scale = s->y_dc_scale_table[quant];
s->c_dc_scale = s->c_dc_scale_table[quant];
/* Get DC differential */
if (n < 4) {
dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
} else {
dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
}
if (dcdiff < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");
return -1;
}
if (dcdiff) {
const int m = (quant == 1 || quant == 2) ? 3 - quant : 0;
if (dcdiff == 119 /* ESC index value */) {
dcdiff = get_bits(gb, 8 + m);
} else {
if (m)
dcdiff = (dcdiff << m) + get_bits(gb, m) - ((1 << m) - 1);
}
if (get_bits1(gb))
dcdiff = -dcdiff;
}
/* Prediction */
dcdiff += ff_vc1_pred_dc(&v->s, v->overlap, quant, n, a_avail, c_avail, &dc_val, &dc_pred_dir);
*dc_val = dcdiff;
/* Store the quantized DC coeff, used for prediction */
if (n < 4) {
block[0] = dcdiff * s->y_dc_scale;
} else {
block[0] = dcdiff * s->c_dc_scale;
}
//AC Decoding
i = 1;
/* check if AC is needed at all and adjust direction if needed */
if (!a_avail) dc_pred_dir = 1;
if (!c_avail) dc_pred_dir = 0;
if (!a_avail && !c_avail) use_pred = 0;
ac_val = s->ac_val[0][s->block_index[n]];
ac_val2 = ac_val;
scale = quant * 2 + ((mquant < 0) ? 0 : v->halfpq);
if (dc_pred_dir) //left
ac_val -= 16;
else //top
ac_val -= 16 * s->block_wrap[n];
q1 = s->current_picture.qscale_table[mb_pos];
if (dc_pred_dir && c_avail && mb_pos)
q2 = s->current_picture.qscale_table[mb_pos - 1];
if (!dc_pred_dir && a_avail && mb_pos >= s->mb_stride)
q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride];
if (dc_pred_dir && n == 1)
q2 = q1;
if (!dc_pred_dir && n == 2)
q2 = q1;
if (n == 3) q2 = q1;
if (coded) {
int last = 0, skip, value;
int k;
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
i += skip;
if (i > 63)
break;
if (v->fcm == PROGRESSIVE)
block[v->zz_8x8[0][i++]] = value;
else {
if (use_pred && (v->fcm == ILACE_FRAME)) {
if (!dc_pred_dir) // top
block[v->zz_8x8[2][i++]] = value;
else // left
block[v->zz_8x8[3][i++]] = value;
} else {
block[v->zzi_8x8[i++]] = value;
}
}
}
/* apply AC prediction if needed */
if (use_pred) {
/* scale predictors if needed*/
q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1;
if (q1 < 1)
return AVERROR_INVALIDDATA;
if (q2)
q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1;
if (q2 && q1 != q2) {
if (dc_pred_dir) { // left
for (k = 1; k < 8; k++)
block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
} else { //top
for (k = 1; k < 8; k++)
block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
}
} else {
if (dc_pred_dir) { // left
for (k = 1; k < 8; k++)
block[k << v->left_blk_sh] += ac_val[k];
} else { // top
for (k = 1; k < 8; k++)
block[k << v->top_blk_sh] += ac_val[k + 8];
}
}
}
/* save AC coeffs for further prediction */
for (k = 1; k < 8; k++) {
ac_val2[k ] = block[k << v->left_blk_sh];
ac_val2[k + 8] = block[k << v->top_blk_sh];
}
/* scale AC coeffs */
for (k = 1; k < 64; k++)
if (block[k]) {
block[k] *= scale;
if (!v->pquantizer)
block[k] += (block[k] < 0) ? -quant : quant;
}
if (use_pred) i = 63;
} else { // no AC coeffs
int k;
memset(ac_val2, 0, 16 * 2);
if (dc_pred_dir) { // left
if (use_pred) {
memcpy(ac_val2, ac_val, 8 * 2);
q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1;
if (q1 < 1)
return AVERROR_INVALIDDATA;
if (q2)
q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1;
if (q2 && q1 != q2) {
for (k = 1; k < 8; k++)
ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
}
}
} else { // top
if (use_pred) {
memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);
q1 = FFABS(q1) * 2 + ((q1 < 0) ? 0 : v->halfpq) - 1;
if (q1 < 1)
return AVERROR_INVALIDDATA;
if (q2)
q2 = FFABS(q2) * 2 + ((q2 < 0) ? 0 : v->halfpq) - 1;
if (q2 && q1 != q2) {
for (k = 1; k < 8; k++)
ac_val2[k + 8] = (ac_val2[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
}
}
}
/* apply AC prediction if needed */
if (use_pred) {
if (dc_pred_dir) { // left
for (k = 1; k < 8; k++) {
block[k << v->left_blk_sh] = ac_val2[k] * scale;
if (!v->pquantizer && block[k << v->left_blk_sh])
block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -quant : quant;
}
} else { // top
for (k = 1; k < 8; k++) {
block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;
if (!v->pquantizer && block[k << v->top_blk_sh])
block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -quant : quant;
}
}
i = 63;
}
}
s->block_last_index[n] = i;
return 0;
}
/** Decode P block
*/
static int vc1_decode_p_block(VC1Context *v, int16_t block[64], int n,
int mquant, int ttmb, int first_block,
uint8_t *dst, int linesize, int skip_block,
int *ttmb_out)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i, j;
int subblkpat = 0;
int scale, off, idx, last, skip, value;
int ttblk = ttmb & 7;
int pat = 0;
int quant = FFABS(mquant);
s->bdsp.clear_block(block);
if (ttmb == -1) {
ttblk = ff_vc1_ttblk_to_tt[v->tt_index][get_vlc2(gb, ff_vc1_ttblk_vlc[v->tt_index].table, VC1_TTBLK_VLC_BITS, 1)];
}
if (ttblk == TT_4X4) {
subblkpat = ~(get_vlc2(gb, ff_vc1_subblkpat_vlc[v->tt_index].table, VC1_SUBBLKPAT_VLC_BITS, 1) + 1);
}
if ((ttblk != TT_8X8 && ttblk != TT_4X4)
&& ((v->ttmbf || (ttmb != -1 && (ttmb & 8) && !first_block))
|| (!v->res_rtm_flag && !first_block))) {
subblkpat = decode012(gb);
if (subblkpat)
subblkpat ^= 3; // swap decoded pattern bits
if (ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM)
ttblk = TT_8X4;
if (ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT)
ttblk = TT_4X8;
}
scale = quant * 2 + ((mquant < 0) ? 0 : v->halfpq);
// convert transforms like 8X4_TOP to generic TT and SUBBLKPAT
if (ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) {
subblkpat = 2 - (ttblk == TT_8X4_TOP);
ttblk = TT_8X4;
}
if (ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT) {
subblkpat = 2 - (ttblk == TT_4X8_LEFT);
ttblk = TT_4X8;
}
switch (ttblk) {
case TT_8X8:
pat = 0xF;
i = 0;
last = 0;
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
i += skip;
if (i > 63)
break;
if (!v->fcm)
idx = v->zz_8x8[0][i++];
else
idx = v->zzi_8x8[i++];
block[idx] = value * scale;
if (!v->pquantizer)
block[idx] += (block[idx] < 0) ? -quant : quant;
}
if (!skip_block) {
if (i == 1)
v->vc1dsp.vc1_inv_trans_8x8_dc(dst, linesize, block);
else {
v->vc1dsp.vc1_inv_trans_8x8(block);
s->idsp.add_pixels_clamped(block, dst, linesize);
}
}
break;
case TT_4X4:
pat = ~subblkpat & 0xF;
for (j = 0; j < 4; j++) {
last = subblkpat & (1 << (3 - j));
i = 0;
off = (j & 1) * 4 + (j & 2) * 16;
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
i += skip;
if (i > 15)
break;
if (!v->fcm)
idx = ff_vc1_simple_progressive_4x4_zz[i++];
else
idx = ff_vc1_adv_interlaced_4x4_zz[i++];
block[idx + off] = value * scale;
if (!v->pquantizer)
block[idx + off] += (block[idx + off] < 0) ? -quant : quant;
}
if (!(subblkpat & (1 << (3 - j))) && !skip_block) {
if (i == 1)
v->vc1dsp.vc1_inv_trans_4x4_dc(dst + (j & 1) * 4 + (j & 2) * 2 * linesize, linesize, block + off);
else
v->vc1dsp.vc1_inv_trans_4x4(dst + (j & 1) * 4 + (j & 2) * 2 * linesize, linesize, block + off);
}
}
break;
case TT_8X4:
pat = ~((subblkpat & 2) * 6 + (subblkpat & 1) * 3) & 0xF;
for (j = 0; j < 2; j++) {
last = subblkpat & (1 << (1 - j));
i = 0;
off = j * 32;
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
i += skip;
if (i > 31)
break;
if (!v->fcm)
idx = v->zz_8x4[i++] + off;
else
idx = ff_vc1_adv_interlaced_8x4_zz[i++] + off;
block[idx] = value * scale;
if (!v->pquantizer)
block[idx] += (block[idx] < 0) ? -quant : quant;
}
if (!(subblkpat & (1 << (1 - j))) && !skip_block) {
if (i == 1)
v->vc1dsp.vc1_inv_trans_8x4_dc(dst + j * 4 * linesize, linesize, block + off);
else
v->vc1dsp.vc1_inv_trans_8x4(dst + j * 4 * linesize, linesize, block + off);
}
}
break;
case TT_4X8:
pat = ~(subblkpat * 5) & 0xF;
for (j = 0; j < 2; j++) {
last = subblkpat & (1 << (1 - j));
i = 0;
off = j * 4;
while (!last) {
vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
i += skip;
if (i > 31)
break;
if (!v->fcm)
idx = v->zz_4x8[i++] + off;
else
idx = ff_vc1_adv_interlaced_4x8_zz[i++] + off;
block[idx] = value * scale;
if (!v->pquantizer)
block[idx] += (block[idx] < 0) ? -quant : quant;
}
if (!(subblkpat & (1 << (1 - j))) && !skip_block) {
if (i == 1)
v->vc1dsp.vc1_inv_trans_4x8_dc(dst + j * 4, linesize, block + off);
else
v->vc1dsp.vc1_inv_trans_4x8(dst + j*4, linesize, block + off);
}
}
break;
}
if (ttmb_out)
*ttmb_out |= ttblk << (n * 4);
return pat;
}
/** @} */ // Macroblock group
static const uint8_t size_table[6] = { 0, 2, 3, 4, 5, 8 };
/** Decode one P-frame MB
*/
static int vc1_decode_p_mb(VC1Context *v)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i, j;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int cbp; /* cbp decoding stuff */
int mqdiff, mquant; /* MB quantization */
int ttmb = v->ttfrm; /* MB Transform type */
int mb_has_coeffs = 1; /* last_flag */
int dmv_x, dmv_y; /* Differential MV components */
int index, index1; /* LUT indexes */
int val, sign; /* temp values */
int first_block = 1;
int dst_idx, off;
int skipped, fourmv;
int block_cbp = 0, pat, block_tt = 0, block_intra = 0;
mquant = v->pq; /* lossy initialization */
if (v->mv_type_is_raw)
fourmv = get_bits1(gb);
else
fourmv = v->mv_type_mb_plane[mb_pos];
if (v->skip_is_raw)
skipped = get_bits1(gb);
else
skipped = v->s.mbskip_table[mb_pos];
if (!fourmv) { /* 1MV mode */
if (!skipped) {
GET_MVDATA(dmv_x, dmv_y);
if (s->mb_intra) {
s->current_picture.motion_val[1][s->block_index[0]][0] = 0;
s->current_picture.motion_val[1][s->block_index[0]][1] = 0;
}
s->current_picture.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16;
ff_vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0, 0);
/* FIXME Set DC val for inter block ? */
if (s->mb_intra && !mb_has_coeffs) {
GET_MQUANT();
s->ac_pred = get_bits1(gb);
cbp = 0;
} else if (mb_has_coeffs) {
if (s->mb_intra)
s->ac_pred = get_bits1(gb);
cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
GET_MQUANT();
} else {
mquant = v->pq;
cbp = 0;
}
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table,
VC1_TTMB_VLC_BITS, 2);
if (!s->mb_intra) ff_vc1_mc_1mv(v, 0);
dst_idx = 0;
for (i = 0; i < 6; i++) {
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
v->mb_type[0][s->block_index[i]] = s->mb_intra;
if (s->mb_intra) {
/* check if prediction blocks A and C are available */
v->a_avail = v->c_avail = 0;
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, val, mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]);
if (v->rangeredfrm)
for (j = 0; j < 64; j++)
v->block[v->cur_blk_idx][block_map[i]][j] <<= 1;
block_cbp |= 0xF << (i << 2);
block_intra |= 1 << i;
} else if (val) {
pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb, first_block,
s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize,
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt);
block_cbp |= pat << (i << 2);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
} else { // skipped
s->mb_intra = 0;
for (i = 0; i < 6; i++) {
v->mb_type[0][s->block_index[i]] = 0;
s->dc_val[0][s->block_index[i]] = 0;
}
s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;
s->current_picture.qscale_table[mb_pos] = 0;
ff_vc1_pred_mv(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0, 0);
ff_vc1_mc_1mv(v, 0);
}
} else { // 4MV mode
if (!skipped /* unskipped MB */) {
int intra_count = 0, coded_inter = 0;
int is_intra[6], is_coded[6];
/* Get CBPCY */
cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
for (i = 0; i < 6; i++) {
val = ((cbp >> (5 - i)) & 1);
s->dc_val[0][s->block_index[i]] = 0;
s->mb_intra = 0;
if (i < 4) {
dmv_x = dmv_y = 0;
s->mb_intra = 0;
mb_has_coeffs = 0;
if (val) {
GET_MVDATA(dmv_x, dmv_y);
}
ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0, 0);
if (!s->mb_intra)
ff_vc1_mc_4mv_luma(v, i, 0, 0);
intra_count += s->mb_intra;
is_intra[i] = s->mb_intra;
is_coded[i] = mb_has_coeffs;
}
if (i & 4) {
is_intra[i] = (intra_count >= 3);
is_coded[i] = val;
}
if (i == 4)
ff_vc1_mc_4mv_chroma(v, 0);
v->mb_type[0][s->block_index[i]] = is_intra[i];
if (!coded_inter)
coded_inter = !is_intra[i] & is_coded[i];
}
// if there are no coded blocks then don't do anything more
dst_idx = 0;
if (!intra_count && !coded_inter)
goto end;
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
/* test if block is intra and has pred */
{
int intrapred = 0;
for (i = 0; i < 6; i++)
if (is_intra[i]) {
if (((!s->first_slice_line || (i == 2 || i == 3)) && v->mb_type[0][s->block_index[i] - s->block_wrap[i]])
|| ((s->mb_x || (i == 1 || i == 3)) && v->mb_type[0][s->block_index[i] - 1])) {
intrapred = 1;
break;
}
}
if (intrapred)
s->ac_pred = get_bits1(gb);
else
s->ac_pred = 0;
}
if (!v->ttmbf && coded_inter)
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
for (i = 0; i < 6; i++) {
dst_idx += i >> 2;
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
s->mb_intra = is_intra[i];
if (is_intra[i]) {
/* check if prediction blocks A and C are available */
v->a_avail = v->c_avail = 0;
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, is_coded[i], mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]);
if (v->rangeredfrm)
for (j = 0; j < 64; j++)
v->block[v->cur_blk_idx][block_map[i]][j] <<= 1;
block_cbp |= 0xF << (i << 2);
block_intra |= 1 << i;
} else if (is_coded[i]) {
pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb,
first_block, s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize : s->linesize,
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY),
&block_tt);
block_cbp |= pat << (i << 2);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
} else { // skipped MB
s->mb_intra = 0;
s->current_picture.qscale_table[mb_pos] = 0;
for (i = 0; i < 6; i++) {
v->mb_type[0][s->block_index[i]] = 0;
s->dc_val[0][s->block_index[i]] = 0;
}
for (i = 0; i < 4; i++) {
ff_vc1_pred_mv(v, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0], 0, 0);
ff_vc1_mc_4mv_luma(v, i, 0, 0);
}
ff_vc1_mc_4mv_chroma(v, 0);
s->current_picture.qscale_table[mb_pos] = 0;
}
}
end:
if (v->overlap && v->pq >= 9)
ff_vc1_p_overlap_filter(v);
vc1_put_blocks_clamped(v, 1);
v->cbp[s->mb_x] = block_cbp;
v->ttblk[s->mb_x] = block_tt;
v->is_intra[s->mb_x] = block_intra;
return 0;
}
/* Decode one macroblock in an interlaced frame p picture */
static int vc1_decode_p_mb_intfr(VC1Context *v)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int cbp = 0; /* cbp decoding stuff */
int mqdiff, mquant; /* MB quantization */
int ttmb = v->ttfrm; /* MB Transform type */
int mb_has_coeffs = 1; /* last_flag */
int dmv_x, dmv_y; /* Differential MV components */
int val; /* temp value */
int first_block = 1;
int dst_idx, off;
int skipped, fourmv = 0, twomv = 0;
int block_cbp = 0, pat, block_tt = 0;
int idx_mbmode = 0, mvbp;
int fieldtx;
mquant = v->pq; /* Lossy initialization */
if (v->skip_is_raw)
skipped = get_bits1(gb);
else
skipped = v->s.mbskip_table[mb_pos];
if (!skipped) {
if (v->fourmvswitch)
idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_4MV_MBMODE_VLC_BITS, 2); // try getting this done
else
idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); // in a single line
switch (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0]) {
/* store the motion vector type in a flag (useful later) */
case MV_PMODE_INTFR_4MV:
fourmv = 1;
v->blk_mv_type[s->block_index[0]] = 0;
v->blk_mv_type[s->block_index[1]] = 0;
v->blk_mv_type[s->block_index[2]] = 0;
v->blk_mv_type[s->block_index[3]] = 0;
break;
case MV_PMODE_INTFR_4MV_FIELD:
fourmv = 1;
v->blk_mv_type[s->block_index[0]] = 1;
v->blk_mv_type[s->block_index[1]] = 1;
v->blk_mv_type[s->block_index[2]] = 1;
v->blk_mv_type[s->block_index[3]] = 1;
break;
case MV_PMODE_INTFR_2MV_FIELD:
twomv = 1;
v->blk_mv_type[s->block_index[0]] = 1;
v->blk_mv_type[s->block_index[1]] = 1;
v->blk_mv_type[s->block_index[2]] = 1;
v->blk_mv_type[s->block_index[3]] = 1;
break;
case MV_PMODE_INTFR_1MV:
v->blk_mv_type[s->block_index[0]] = 0;
v->blk_mv_type[s->block_index[1]] = 0;
v->blk_mv_type[s->block_index[2]] = 0;
v->blk_mv_type[s->block_index[3]] = 0;
break;
}
if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB
for (i = 0; i < 4; i++) {
s->current_picture.motion_val[1][s->block_index[i]][0] = 0;
s->current_picture.motion_val[1][s->block_index[i]][1] = 0;
}
v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1.
s->mb_intra = 1;
s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;
fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb);
mb_has_coeffs = get_bits1(gb);
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
/* Set DC scale - y and c use the same (not sure if necessary here) */
s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)];
s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)];
dst_idx = 0;
for (i = 0; i < 6; i++) {
v->a_avail = v->c_avail = 0;
v->mb_type[0][s->block_index[i]] = 1;
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, val, mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]);
if (i < 4)
off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize;
else
off = 0;
block_cbp |= 0xf << (i << 2);
}
} else { // inter MB
mb_has_coeffs = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][3];
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {
v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1);
} else {
if ((ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV)
|| (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV_FIELD)) {
v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
}
}
s->mb_intra = v->is_intra[s->mb_x] = 0;
for (i = 0; i < 6; i++)
v->mb_type[0][s->block_index[i]] = 0;
fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][1];
/* for all motion vector read MVDATA and motion compensate each block */
dst_idx = 0;
if (fourmv) {
mvbp = v->fourmvbp;
for (i = 0; i < 4; i++) {
dmv_x = dmv_y = 0;
if (mvbp & (8 >> i))
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
ff_vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_mc_4mv_luma(v, i, 0, 0);
}
ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);
} else if (twomv) {
mvbp = v->twomvbp;
dmv_x = dmv_y = 0;
if (mvbp & 2) {
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
}
ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_mc_4mv_luma(v, 0, 0, 0);
ff_vc1_mc_4mv_luma(v, 1, 0, 0);
dmv_x = dmv_y = 0;
if (mvbp & 1) {
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
}
ff_vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_mc_4mv_luma(v, 2, 0, 0);
ff_vc1_mc_4mv_luma(v, 3, 0, 0);
ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);
} else {
mvbp = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][2];
dmv_x = dmv_y = 0;
if (mvbp) {
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
}
ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_mc_1mv(v, 0);
}
if (cbp)
GET_MQUANT(); // p. 227
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf && cbp)
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
for (i = 0; i < 6; i++) {
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
if (!fieldtx)
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
else
off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize));
if (val) {
pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb,
first_block, s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize : (s->linesize << fieldtx),
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt);
block_cbp |= pat << (i << 2);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
}
} else { // skipped
s->mb_intra = v->is_intra[s->mb_x] = 0;
for (i = 0; i < 6; i++) {
v->mb_type[0][s->block_index[i]] = 0;
s->dc_val[0][s->block_index[i]] = 0;
}
s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;
s->current_picture.qscale_table[mb_pos] = 0;
v->blk_mv_type[s->block_index[0]] = 0;
v->blk_mv_type[s->block_index[1]] = 0;
v->blk_mv_type[s->block_index[2]] = 0;
v->blk_mv_type[s->block_index[3]] = 0;
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_mc_1mv(v, 0);
v->fieldtx_plane[mb_pos] = 0;
}
if (v->overlap && v->pq >= 9)
ff_vc1_p_overlap_filter(v);
vc1_put_blocks_clamped(v, 1);
v->cbp[s->mb_x] = block_cbp;
v->ttblk[s->mb_x] = block_tt;
return 0;
}
static int vc1_decode_p_mb_intfi(VC1Context *v)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int cbp = 0; /* cbp decoding stuff */
int mqdiff, mquant; /* MB quantization */
int ttmb = v->ttfrm; /* MB Transform type */
int mb_has_coeffs = 1; /* last_flag */
int dmv_x, dmv_y; /* Differential MV components */
int val; /* temp values */
int first_block = 1;
int dst_idx, off;
int pred_flag = 0;
int block_cbp = 0, pat, block_tt = 0;
int idx_mbmode = 0;
mquant = v->pq; /* Lossy initialization */
idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);
if (idx_mbmode <= 1) { // intra MB
v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1.
s->mb_intra = 1;
s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;
s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;
s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA;
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
/* Set DC scale - y and c use the same (not sure if necessary here) */
s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)];
s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)];
v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);
mb_has_coeffs = idx_mbmode & 1;
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2);
dst_idx = 0;
for (i = 0; i < 6; i++) {
v->a_avail = v->c_avail = 0;
v->mb_type[0][s->block_index[i]] = 1;
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, v->block[v->cur_blk_idx][block_map[i]], i, val, mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[i]]);
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
block_cbp |= 0xf << (i << 2);
}
} else {
s->mb_intra = v->is_intra[s->mb_x] = 0;
s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;
for (i = 0; i < 6; i++)
v->mb_type[0][s->block_index[i]] = 0;
if (idx_mbmode <= 5) { // 1-MV
dmv_x = dmv_y = pred_flag = 0;
if (idx_mbmode & 1) {
get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);
}
ff_vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);
ff_vc1_mc_1mv(v, 0);
mb_has_coeffs = !(idx_mbmode & 2);
} else { // 4-MV
v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
for (i = 0; i < 4; i++) {
dmv_x = dmv_y = pred_flag = 0;
if (v->fourmvbp & (8 >> i))
get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);
ff_vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);
ff_vc1_mc_4mv_luma(v, i, 0, 0);
}
ff_vc1_mc_4mv_chroma(v, 0);
mb_has_coeffs = idx_mbmode & 1;
}
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
if (cbp) {
GET_MQUANT();
}
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf && cbp) {
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
}
dst_idx = 0;
for (i = 0; i < 6; i++) {
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;
if (val) {
pat = vc1_decode_p_block(v, v->block[v->cur_blk_idx][block_map[i]], i, mquant, ttmb,
first_block, s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize : s->linesize,
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY),
&block_tt);
block_cbp |= pat << (i << 2);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
}
if (v->overlap && v->pq >= 9)
ff_vc1_p_overlap_filter(v);
vc1_put_blocks_clamped(v, 1);
v->cbp[s->mb_x] = block_cbp;
v->ttblk[s->mb_x] = block_tt;
return 0;
}
/** Decode one B-frame MB (in Main profile)
*/
static void vc1_decode_b_mb(VC1Context *v)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i, j;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int cbp = 0; /* cbp decoding stuff */
int mqdiff, mquant; /* MB quantization */
int ttmb = v->ttfrm; /* MB Transform type */
int mb_has_coeffs = 0; /* last_flag */
int index, index1; /* LUT indexes */
int val, sign; /* temp values */
int first_block = 1;
int dst_idx, off;
int skipped, direct;
int dmv_x[2], dmv_y[2];
int bmvtype = BMV_TYPE_BACKWARD;
mquant = v->pq; /* lossy initialization */
s->mb_intra = 0;
if (v->dmb_is_raw)
direct = get_bits1(gb);
else
direct = v->direct_mb_plane[mb_pos];
if (v->skip_is_raw)
skipped = get_bits1(gb);
else
skipped = v->s.mbskip_table[mb_pos];
dmv_x[0] = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0;
for (i = 0; i < 6; i++) {
v->mb_type[0][s->block_index[i]] = 0;
s->dc_val[0][s->block_index[i]] = 0;
}
s->current_picture.qscale_table[mb_pos] = 0;
if (!direct) {
if (!skipped) {
GET_MVDATA(dmv_x[0], dmv_y[0]);
dmv_x[1] = dmv_x[0];
dmv_y[1] = dmv_y[0];
}
if (skipped || !s->mb_intra) {
bmvtype = decode012(gb);
switch (bmvtype) {
case 0:
bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD;
break;
case 1:
bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD;
break;
case 2:
bmvtype = BMV_TYPE_INTERPOLATED;
dmv_x[0] = dmv_y[0] = 0;
}
}
}
for (i = 0; i < 6; i++)
v->mb_type[0][s->block_index[i]] = s->mb_intra;
if (skipped) {
if (direct)
bmvtype = BMV_TYPE_INTERPOLATED;
ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
return;
}
if (direct) {
cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
GET_MQUANT();
s->mb_intra = 0;
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf)
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
dmv_x[0] = dmv_y[0] = dmv_x[1] = dmv_y[1] = 0;
ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
} else {
if (!mb_has_coeffs && !s->mb_intra) {
/* no coded blocks - effectively skipped */
ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
return;
}
if (s->mb_intra && !mb_has_coeffs) {
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
s->ac_pred = get_bits1(gb);
cbp = 0;
ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
} else {
if (bmvtype == BMV_TYPE_INTERPOLATED) {
GET_MVDATA(dmv_x[0], dmv_y[0]);
if (!mb_has_coeffs) {
/* interpolated skipped block */
ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
return;
}
}
ff_vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
if (!s->mb_intra) {
vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
}
if (s->mb_intra)
s->ac_pred = get_bits1(gb);
cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
}
}
dst_idx = 0;
for (i = 0; i < 6; i++) {
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
v->mb_type[0][s->block_index[i]] = s->mb_intra;
if (s->mb_intra) {
/* check if prediction blocks A and C are available */
v->a_avail = v->c_avail = 0;
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, s->block[i], i, val, mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
if (v->rangeredfrm)
for (j = 0; j < 64; j++)
s->block[i][j] <<= 1;
s->idsp.put_signed_pixels_clamped(s->block[i],
s->dest[dst_idx] + off,
i & 4 ? s->uvlinesize
: s->linesize);
} else if (val) {
vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
first_block, s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize : s->linesize,
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), NULL);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
}
/** Decode one B-frame MB (in interlaced field B picture)
*/
static void vc1_decode_b_mb_intfi(VC1Context *v)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i, j;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int cbp = 0; /* cbp decoding stuff */
int mqdiff, mquant; /* MB quantization */
int ttmb = v->ttfrm; /* MB Transform type */
int mb_has_coeffs = 0; /* last_flag */
int val; /* temp value */
int first_block = 1;
int dst_idx, off;
int fwd;
int dmv_x[2], dmv_y[2], pred_flag[2];
int bmvtype = BMV_TYPE_BACKWARD;
int block_cbp = 0, pat, block_tt = 0;
int idx_mbmode;
mquant = v->pq; /* Lossy initialization */
s->mb_intra = 0;
idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);
if (idx_mbmode <= 1) { // intra MB
v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1.
s->mb_intra = 1;
s->current_picture.motion_val[1][s->block_index[0]][0] = 0;
s->current_picture.motion_val[1][s->block_index[0]][1] = 0;
s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA;
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
/* Set DC scale - y and c use the same (not sure if necessary here) */
s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)];
s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)];
v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);
mb_has_coeffs = idx_mbmode & 1;
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2);
dst_idx = 0;
for (i = 0; i < 6; i++) {
v->a_avail = v->c_avail = 0;
v->mb_type[0][s->block_index[i]] = 1;
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, s->block[i], i, val, mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && (i > 3) && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
if (v->rangeredfrm)
for (j = 0; j < 64; j++)
s->block[i][j] <<= 1;
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
s->idsp.put_signed_pixels_clamped(s->block[i],
s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize
: s->linesize);
}
} else {
s->mb_intra = v->is_intra[s->mb_x] = 0;
s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;
for (i = 0; i < 6; i++)
v->mb_type[0][s->block_index[i]] = 0;
if (v->fmb_is_raw)
fwd = v->forward_mb_plane[mb_pos] = get_bits1(gb);
else
fwd = v->forward_mb_plane[mb_pos];
if (idx_mbmode <= 5) { // 1-MV
int interpmvp = 0;
dmv_x[0] = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0;
pred_flag[0] = pred_flag[1] = 0;
if (fwd)
bmvtype = BMV_TYPE_FORWARD;
else {
bmvtype = decode012(gb);
switch (bmvtype) {
case 0:
bmvtype = BMV_TYPE_BACKWARD;
break;
case 1:
bmvtype = BMV_TYPE_DIRECT;
break;
case 2:
bmvtype = BMV_TYPE_INTERPOLATED;
interpmvp = get_bits1(gb);
}
}
v->bmvtype = bmvtype;
if (bmvtype != BMV_TYPE_DIRECT && idx_mbmode & 1) {
get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD], &dmv_y[bmvtype == BMV_TYPE_BACKWARD], &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);
}
if (interpmvp) {
get_mvdata_interlaced(v, &dmv_x[1], &dmv_y[1], &pred_flag[1]);
}
if (bmvtype == BMV_TYPE_DIRECT) {
dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;
dmv_x[1] = dmv_y[1] = pred_flag[0] = 0;
if (!s->next_picture_ptr->field_picture) {
av_log(s->avctx, AV_LOG_ERROR, "Mixed field/frame direct mode not supported\n");
return;
}
}
ff_vc1_pred_b_mv_intfi(v, 0, dmv_x, dmv_y, 1, pred_flag);
vc1_b_mc(v, dmv_x, dmv_y, (bmvtype == BMV_TYPE_DIRECT), bmvtype);
mb_has_coeffs = !(idx_mbmode & 2);
} else { // 4-MV
if (fwd)
bmvtype = BMV_TYPE_FORWARD;
v->bmvtype = bmvtype;
v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
for (i = 0; i < 4; i++) {
dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;
dmv_x[1] = dmv_y[1] = pred_flag[1] = 0;
if (v->fourmvbp & (8 >> i)) {
get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD],
&dmv_y[bmvtype == BMV_TYPE_BACKWARD],
&pred_flag[bmvtype == BMV_TYPE_BACKWARD]);
}
ff_vc1_pred_b_mv_intfi(v, i, dmv_x, dmv_y, 0, pred_flag);
ff_vc1_mc_4mv_luma(v, i, bmvtype == BMV_TYPE_BACKWARD, 0);
}
ff_vc1_mc_4mv_chroma(v, bmvtype == BMV_TYPE_BACKWARD);
mb_has_coeffs = idx_mbmode & 1;
}
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
if (cbp) {
GET_MQUANT();
}
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf && cbp) {
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
}
dst_idx = 0;
for (i = 0; i < 6; i++) {
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;
if (val) {
pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
first_block, s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize : s->linesize,
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt);
block_cbp |= pat << (i << 2);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
}
v->cbp[s->mb_x] = block_cbp;
v->ttblk[s->mb_x] = block_tt;
}
/** Decode one B-frame MB (in interlaced frame B picture)
*/
static int vc1_decode_b_mb_intfr(VC1Context *v)
{
MpegEncContext *s = &v->s;
GetBitContext *gb = &s->gb;
int i, j;
int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
int cbp = 0; /* cbp decoding stuff */
int mqdiff, mquant; /* MB quantization */
int ttmb = v->ttfrm; /* MB Transform type */
int mvsw = 0; /* motion vector switch */
int mb_has_coeffs = 1; /* last_flag */
int dmv_x, dmv_y; /* Differential MV components */
int val; /* temp value */
int first_block = 1;
int dst_idx, off;
int skipped, direct, twomv = 0;
int block_cbp = 0, pat, block_tt = 0;
int idx_mbmode = 0, mvbp;
int stride_y, fieldtx;
int bmvtype = BMV_TYPE_BACKWARD;
int dir, dir2;
mquant = v->pq; /* Lossy initialization */
s->mb_intra = 0;
if (v->skip_is_raw)
skipped = get_bits1(gb);
else
skipped = v->s.mbskip_table[mb_pos];
if (!skipped) {
idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2);
if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {
twomv = 1;
v->blk_mv_type[s->block_index[0]] = 1;
v->blk_mv_type[s->block_index[1]] = 1;
v->blk_mv_type[s->block_index[2]] = 1;
v->blk_mv_type[s->block_index[3]] = 1;
} else {
v->blk_mv_type[s->block_index[0]] = 0;
v->blk_mv_type[s->block_index[1]] = 0;
v->blk_mv_type[s->block_index[2]] = 0;
v->blk_mv_type[s->block_index[3]] = 0;
}
}
if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB
for (i = 0; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = 0;
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = 0;
s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = 0;
s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = 0;
}
v->is_intra[s->mb_x] = 0x3f; // Set the bitfield to all 1.
s->mb_intra = 1;
s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;
fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb);
mb_has_coeffs = get_bits1(gb);
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
/* Set DC scale - y and c use the same (not sure if necessary here) */
s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)];
s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)];
dst_idx = 0;
for (i = 0; i < 6; i++) {
v->a_avail = v->c_avail = 0;
v->mb_type[0][s->block_index[i]] = 1;
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
if (i == 2 || i == 3 || !s->first_slice_line)
v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
if (i == 1 || i == 3 || s->mb_x)
v->c_avail = v->mb_type[0][s->block_index[i] - 1];
vc1_decode_intra_block(v, s->block[i], i, val, mquant,
(i & 4) ? v->codingset2 : v->codingset);
if (CONFIG_GRAY && i > 3 && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
if (i < 4) {
stride_y = s->linesize << fieldtx;
off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize;
} else {
stride_y = s->uvlinesize;
off = 0;
}
s->idsp.put_signed_pixels_clamped(s->block[i],
s->dest[dst_idx] + off,
stride_y);
}
} else {
s->mb_intra = v->is_intra[s->mb_x] = 0;
if (v->dmb_is_raw)
direct = get_bits1(gb);
else
direct = v->direct_mb_plane[mb_pos];
if (direct) {
if (s->next_picture_ptr->field_picture)
av_log(s->avctx, AV_LOG_WARNING, "Mixed frame/field direct mode not supported\n");
s->mv[0][0][0] = s->current_picture.motion_val[0][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 0, s->quarter_sample);
s->mv[0][0][1] = s->current_picture.motion_val[0][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 0, s->quarter_sample);
s->mv[1][0][0] = s->current_picture.motion_val[1][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 1, s->quarter_sample);
s->mv[1][0][1] = s->current_picture.motion_val[1][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 1, s->quarter_sample);
if (twomv) {
s->mv[0][2][0] = s->current_picture.motion_val[0][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 0, s->quarter_sample);
s->mv[0][2][1] = s->current_picture.motion_val[0][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 0, s->quarter_sample);
s->mv[1][2][0] = s->current_picture.motion_val[1][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 1, s->quarter_sample);
s->mv[1][2][1] = s->current_picture.motion_val[1][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 1, s->quarter_sample);
for (i = 1; i < 4; i += 2) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = s->mv[0][i-1][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = s->mv[0][i-1][1];
s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = s->mv[1][i-1][0];
s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = s->mv[1][i-1][1];
}
} else {
for (i = 1; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = s->mv[0][0][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = s->mv[0][0][1];
s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = s->mv[1][0][0];
s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = s->mv[1][0][1];
}
}
}
if (!direct) {
if (skipped || !s->mb_intra) {
bmvtype = decode012(gb);
switch (bmvtype) {
case 0:
bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD;
break;
case 1:
bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD;
break;
case 2:
bmvtype = BMV_TYPE_INTERPOLATED;
}
}
if (twomv && bmvtype != BMV_TYPE_INTERPOLATED)
mvsw = get_bits1(gb);
}
if (!skipped) { // inter MB
mb_has_coeffs = ff_vc1_mbmode_intfrp[0][idx_mbmode][3];
if (mb_has_coeffs)
cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
if (!direct) {
if (bmvtype == BMV_TYPE_INTERPOLATED && twomv) {
v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
} else if (bmvtype == BMV_TYPE_INTERPOLATED || twomv) {
v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1);
}
}
for (i = 0; i < 6; i++)
v->mb_type[0][s->block_index[i]] = 0;
fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[0][idx_mbmode][1];
/* for all motion vector read MVDATA and motion compensate each block */
dst_idx = 0;
if (direct) {
if (twomv) {
for (i = 0; i < 4; i++) {
ff_vc1_mc_4mv_luma(v, i, 0, 0);
ff_vc1_mc_4mv_luma(v, i, 1, 1);
}
ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);
ff_vc1_mc_4mv_chroma4(v, 1, 1, 1);
} else {
ff_vc1_mc_1mv(v, 0);
ff_vc1_interp_mc(v);
}
} else if (twomv && bmvtype == BMV_TYPE_INTERPOLATED) {
mvbp = v->fourmvbp;
for (i = 0; i < 4; i++) {
dir = i==1 || i==3;
dmv_x = dmv_y = 0;
val = ((mvbp >> (3 - i)) & 1);
if (val)
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
j = i > 1 ? 2 : 0;
ff_vc1_pred_mv_intfr(v, j, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir);
ff_vc1_mc_4mv_luma(v, j, dir, dir);
ff_vc1_mc_4mv_luma(v, j+1, dir, dir);
}
ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);
ff_vc1_mc_4mv_chroma4(v, 1, 1, 1);
} else if (bmvtype == BMV_TYPE_INTERPOLATED) {
mvbp = v->twomvbp;
dmv_x = dmv_y = 0;
if (mvbp & 2)
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_mc_1mv(v, 0);
dmv_x = dmv_y = 0;
if (mvbp & 1)
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 1);
ff_vc1_interp_mc(v);
} else if (twomv) {
dir = bmvtype == BMV_TYPE_BACKWARD;
dir2 = dir;
if (mvsw)
dir2 = !dir;
mvbp = v->twomvbp;
dmv_x = dmv_y = 0;
if (mvbp & 2)
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir);
dmv_x = dmv_y = 0;
if (mvbp & 1)
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
ff_vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir2);
if (mvsw) {
for (i = 0; i < 2; i++) {
s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0];
s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1];
s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0];
s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1];
}
} else {
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir);
ff_vc1_pred_mv_intfr(v, 2, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir);
}
ff_vc1_mc_4mv_luma(v, 0, dir, 0);
ff_vc1_mc_4mv_luma(v, 1, dir, 0);
ff_vc1_mc_4mv_luma(v, 2, dir2, 0);
ff_vc1_mc_4mv_luma(v, 3, dir2, 0);
ff_vc1_mc_4mv_chroma4(v, dir, dir2, 0);
} else {
dir = bmvtype == BMV_TYPE_BACKWARD;
mvbp = ff_vc1_mbmode_intfrp[0][idx_mbmode][2];
dmv_x = dmv_y = 0;
if (mvbp)
get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], dir);
v->blk_mv_type[s->block_index[0]] = 1;
v->blk_mv_type[s->block_index[1]] = 1;
v->blk_mv_type[s->block_index[2]] = 1;
v->blk_mv_type[s->block_index[3]] = 1;
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir);
for (i = 0; i < 2; i++) {
s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0];
s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1];
}
ff_vc1_mc_1mv(v, dir);
}
if (cbp)
GET_MQUANT(); // p. 227
s->current_picture.qscale_table[mb_pos] = mquant;
if (!v->ttmbf && cbp)
ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
for (i = 0; i < 6; i++) {
s->dc_val[0][s->block_index[i]] = 0;
dst_idx += i >> 2;
val = ((cbp >> (5 - i)) & 1);
if (!fieldtx)
off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
else
off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize));
if (val) {
pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
first_block, s->dest[dst_idx] + off,
(i & 4) ? s->uvlinesize : (s->linesize << fieldtx),
CONFIG_GRAY && (i & 4) && (s->avctx->flags & AV_CODEC_FLAG_GRAY), &block_tt);
block_cbp |= pat << (i << 2);
if (!v->ttmbf && ttmb < 8)
ttmb = -1;
first_block = 0;
}
}
} else { // skipped
dir = 0;
for (i = 0; i < 6; i++) {
v->mb_type[0][s->block_index[i]] = 0;
s->dc_val[0][s->block_index[i]] = 0;
}
s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;
s->current_picture.qscale_table[mb_pos] = 0;
v->blk_mv_type[s->block_index[0]] = 0;
v->blk_mv_type[s->block_index[1]] = 0;
v->blk_mv_type[s->block_index[2]] = 0;
v->blk_mv_type[s->block_index[3]] = 0;
if (!direct) {
if (bmvtype == BMV_TYPE_INTERPOLATED) {
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0);
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 1);
} else {
dir = bmvtype == BMV_TYPE_BACKWARD;
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], dir);
if (mvsw) {
int dir2 = dir;
if (mvsw)
dir2 = !dir;
for (i = 0; i < 2; i++) {
s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0];
s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1];
s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0];
s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1];
}
} else {
v->blk_mv_type[s->block_index[0]] = 1;
v->blk_mv_type[s->block_index[1]] = 1;
v->blk_mv_type[s->block_index[2]] = 1;
v->blk_mv_type[s->block_index[3]] = 1;
ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir);
for (i = 0; i < 2; i++) {
s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0];
s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1];
}
}
}
}
ff_vc1_mc_1mv(v, dir);
if (direct || bmvtype == BMV_TYPE_INTERPOLATED) {
ff_vc1_interp_mc(v);
}
v->fieldtx_plane[mb_pos] = 0;
}
}
v->cbp[s->mb_x] = block_cbp;
v->ttblk[s->mb_x] = block_tt;
return 0;
}
/** Decode blocks of I-frame
*/
static void vc1_decode_i_blocks(VC1Context *v)
{
int k, j;
MpegEncContext *s = &v->s;
int cbp, val;
uint8_t *coded_val;
int mb_pos;
/* select coding mode used for VLC tables selection */
switch (v->y_ac_table_index) {
case 0:
v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
break;
case 1:
v->codingset = CS_HIGH_MOT_INTRA;
break;
case 2:
v->codingset = CS_MID_RATE_INTRA;
break;
}
switch (v->c_ac_table_index) {
case 0:
v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
break;
case 1:
v->codingset2 = CS_HIGH_MOT_INTER;
break;
case 2:
v->codingset2 = CS_MID_RATE_INTER;
break;
}
/* Set DC scale - y and c use the same */
s->y_dc_scale = s->y_dc_scale_table[v->pq];
s->c_dc_scale = s->c_dc_scale_table[v->pq];
//do frame decode
s->mb_x = s->mb_y = 0;
s->mb_intra = 1;
s->first_slice_line = 1;
for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
s->mb_x = 0;
init_block_index(v);
for (; s->mb_x < v->end_mb_x; s->mb_x++) {
ff_update_block_index(s);
s->bdsp.clear_blocks(v->block[v->cur_blk_idx][0]);
mb_pos = s->mb_x + s->mb_y * s->mb_width;
s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;
s->current_picture.qscale_table[mb_pos] = v->pq;
for (int i = 0; i < 4; i++) {
s->current_picture.motion_val[1][s->block_index[i]][0] = 0;
s->current_picture.motion_val[1][s->block_index[i]][1] = 0;
}
// do actual MB decoding and displaying
cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);
v->s.ac_pred = get_bits1(&v->s.gb);
for (k = 0; k < 6; k++) {
v->mb_type[0][s->block_index[k]] = 1;
val = ((cbp >> (5 - k)) & 1);
if (k < 4) {
int pred = vc1_coded_block_pred(&v->s, k, &coded_val);
val = val ^ pred;
*coded_val = val;
}
cbp |= val << (5 - k);
vc1_decode_i_block(v, v->block[v->cur_blk_idx][block_map[k]], k, val, (k < 4) ? v->codingset : v->codingset2);
if (CONFIG_GRAY && k > 3 && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[k]]);
}
if (v->overlap && v->pq >= 9) {
ff_vc1_i_overlap_filter(v);
if (v->rangeredfrm)
for (k = 0; k < 6; k++)
for (j = 0; j < 64; j++)
v->block[v->cur_blk_idx][block_map[k]][j] <<= 1;
vc1_put_blocks_clamped(v, 1);
} else {
if (v->rangeredfrm)
for (k = 0; k < 6; k++)
for (j = 0; j < 64; j++)
v->block[v->cur_blk_idx][block_map[k]][j] = (v->block[v->cur_blk_idx][block_map[k]][j] - 64) << 1;
vc1_put_blocks_clamped(v, 0);
}
if (v->s.loop_filter)
ff_vc1_i_loop_filter(v);
if (get_bits_count(&s->gb) > v->bits) {
ff_er_add_slice(&s->er, 0, 0, s->mb_x, s->mb_y, ER_MB_ERROR);
av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n",
get_bits_count(&s->gb), v->bits);
return;
}
v->topleft_blk_idx = (v->topleft_blk_idx + 1) % (v->end_mb_x + 2);
v->top_blk_idx = (v->top_blk_idx + 1) % (v->end_mb_x + 2);
v->left_blk_idx = (v->left_blk_idx + 1) % (v->end_mb_x + 2);
v->cur_blk_idx = (v->cur_blk_idx + 1) % (v->end_mb_x + 2);
}
if (!v->s.loop_filter)
ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16);
else if (s->mb_y)
ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
s->first_slice_line = 0;
}
if (v->s.loop_filter)
ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
/* This is intentionally mb_height and not end_mb_y - unlike in advanced
* profile, these only differ are when decoding MSS2 rectangles. */
ff_er_add_slice(&s->er, 0, 0, s->mb_width - 1, s->mb_height - 1, ER_MB_END);
}
/** Decode blocks of I-frame for advanced profile
*/
static void vc1_decode_i_blocks_adv(VC1Context *v)
{
int k;
MpegEncContext *s = &v->s;
int cbp, val;
uint8_t *coded_val;
int mb_pos;
int mquant;
int mqdiff;
GetBitContext *gb = &s->gb;
/* select coding mode used for VLC tables selection */
switch (v->y_ac_table_index) {
case 0:
v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
break;
case 1:
v->codingset = CS_HIGH_MOT_INTRA;
break;
case 2:
v->codingset = CS_MID_RATE_INTRA;
break;
}
switch (v->c_ac_table_index) {
case 0:
v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
break;
case 1:
v->codingset2 = CS_HIGH_MOT_INTER;
break;
case 2:
v->codingset2 = CS_MID_RATE_INTER;
break;
}
// do frame decode
s->mb_x = s->mb_y = 0;
s->mb_intra = 1;
s->first_slice_line = 1;
s->mb_y = s->start_mb_y;
if (s->start_mb_y) {
s->mb_x = 0;
init_block_index(v);
memset(&s->coded_block[s->block_index[0] - s->b8_stride], 0,
(1 + s->b8_stride) * sizeof(*s->coded_block));
}
for (; s->mb_y < s->end_mb_y; s->mb_y++) {
s->mb_x = 0;
init_block_index(v);
for (;s->mb_x < s->mb_width; s->mb_x++) {
mquant = v->pq;
ff_update_block_index(s);
s->bdsp.clear_blocks(v->block[v->cur_blk_idx][0]);
mb_pos = s->mb_x + s->mb_y * s->mb_stride;
s->current_picture.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA;
for (int i = 0; i < 4; i++) {
s->current_picture.motion_val[1][s->block_index[i] + v->blocks_off][0] = 0;
s->current_picture.motion_val[1][s->block_index[i] + v->blocks_off][1] = 0;
}
// do actual MB decoding and displaying
if (v->fieldtx_is_raw)
v->fieldtx_plane[mb_pos] = get_bits1(&v->s.gb);
cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);
if (v->acpred_is_raw)
v->s.ac_pred = get_bits1(&v->s.gb);
else
v->s.ac_pred = v->acpred_plane[mb_pos];
if (v->condover == CONDOVER_SELECT && v->overflg_is_raw)
v->over_flags_plane[mb_pos] = get_bits1(&v->s.gb);
GET_MQUANT();
s->current_picture.qscale_table[mb_pos] = mquant;
/* Set DC scale - y and c use the same */
s->y_dc_scale = s->y_dc_scale_table[FFABS(mquant)];
s->c_dc_scale = s->c_dc_scale_table[FFABS(mquant)];
for (k = 0; k < 6; k++) {
v->mb_type[0][s->block_index[k]] = 1;
val = ((cbp >> (5 - k)) & 1);
if (k < 4) {
int pred = vc1_coded_block_pred(&v->s, k, &coded_val);
val = val ^ pred;
*coded_val = val;
}
cbp |= val << (5 - k);
v->a_avail = !s->first_slice_line || (k == 2 || k == 3);
v->c_avail = !!s->mb_x || (k == 1 || k == 3);
vc1_decode_i_block_adv(v, v->block[v->cur_blk_idx][block_map[k]], k, val,
(k < 4) ? v->codingset : v->codingset2, mquant);
if (CONFIG_GRAY && k > 3 && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
continue;
v->vc1dsp.vc1_inv_trans_8x8(v->block[v->cur_blk_idx][block_map[k]]);
}
if (v->overlap && (v->pq >= 9 || v->condover != CONDOVER_NONE))
ff_vc1_i_overlap_filter(v);
vc1_put_blocks_clamped(v, 1);
if (v->s.loop_filter)
ff_vc1_i_loop_filter(v);
if (get_bits_count(&s->gb) > v->bits) {
// TODO: may need modification to handle slice coding
ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);
av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n",
get_bits_count(&s->gb), v->bits);
return;
}
inc_blk_idx(v->topleft_blk_idx);
inc_blk_idx(v->top_blk_idx);
inc_blk_idx(v->left_blk_idx);
inc_blk_idx(v->cur_blk_idx);
}
if (!v->s.loop_filter)
ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16);
else if (s->mb_y)
ff_mpeg_draw_horiz_band(s, (s->mb_y-1) * 16, 16);
s->first_slice_line = 0;
}
if (v->s.loop_filter)
ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
(s->end_mb_y << v->field_mode) - 1, ER_MB_END);
}
static void vc1_decode_p_blocks(VC1Context *v)
{
MpegEncContext *s = &v->s;
int apply_loop_filter;
/* select coding mode used for VLC tables selection */
switch (v->c_ac_table_index) {
case 0:
v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
break;
case 1:
v->codingset = CS_HIGH_MOT_INTRA;
break;
case 2:
v->codingset = CS_MID_RATE_INTRA;
break;
}
switch (v->c_ac_table_index) {
case 0:
v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
break;
case 1:
v->codingset2 = CS_HIGH_MOT_INTER;
break;
case 2:
v->codingset2 = CS_MID_RATE_INTER;
break;
}
apply_loop_filter = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY);
s->first_slice_line = 1;
memset(v->cbp_base, 0, sizeof(v->cbp_base[0]) * 3 * s->mb_stride);
for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
s->mb_x = 0;
init_block_index(v);
for (; s->mb_x < s->mb_width; s->mb_x++) {
ff_update_block_index(s);
if (v->fcm == ILACE_FIELD) {
vc1_decode_p_mb_intfi(v);
if (apply_loop_filter)
ff_vc1_p_loop_filter(v);
} else if (v->fcm == ILACE_FRAME) {
vc1_decode_p_mb_intfr(v);
if (apply_loop_filter)
ff_vc1_p_intfr_loop_filter(v);
} else {
vc1_decode_p_mb(v);
if (apply_loop_filter)
ff_vc1_p_loop_filter(v);
}
if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {
// TODO: may need modification to handle slice coding
ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);
av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n",
get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y);
return;
}
inc_blk_idx(v->topleft_blk_idx);
inc_blk_idx(v->top_blk_idx);
inc_blk_idx(v->left_blk_idx);
inc_blk_idx(v->cur_blk_idx);
}
memmove(v->cbp_base,
v->cbp - s->mb_stride,
sizeof(v->cbp_base[0]) * 2 * s->mb_stride);
memmove(v->ttblk_base,
v->ttblk - s->mb_stride,
sizeof(v->ttblk_base[0]) * 2 * s->mb_stride);
memmove(v->is_intra_base,
v->is_intra - s->mb_stride,
sizeof(v->is_intra_base[0]) * 2 * s->mb_stride);
memmove(v->luma_mv_base,
v->luma_mv - s->mb_stride,
sizeof(v->luma_mv_base[0]) * 2 * s->mb_stride);
if (s->mb_y != s->start_mb_y)
ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
s->first_slice_line = 0;
}
if (s->end_mb_y >= s->start_mb_y)
ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
(s->end_mb_y << v->field_mode) - 1, ER_MB_END);
}
static void vc1_decode_b_blocks(VC1Context *v)
{
MpegEncContext *s = &v->s;
/* select coding mode used for VLC tables selection */
switch (v->c_ac_table_index) {
case 0:
v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
break;
case 1:
v->codingset = CS_HIGH_MOT_INTRA;
break;
case 2:
v->codingset = CS_MID_RATE_INTRA;
break;
}
switch (v->c_ac_table_index) {
case 0:
v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
break;
case 1:
v->codingset2 = CS_HIGH_MOT_INTER;
break;
case 2:
v->codingset2 = CS_MID_RATE_INTER;
break;
}
s->first_slice_line = 1;
for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
s->mb_x = 0;
init_block_index(v);
for (; s->mb_x < s->mb_width; s->mb_x++) {
ff_update_block_index(s);
if (v->fcm == ILACE_FIELD) {
vc1_decode_b_mb_intfi(v);
if (v->s.loop_filter)
ff_vc1_b_intfi_loop_filter(v);
} else if (v->fcm == ILACE_FRAME) {
vc1_decode_b_mb_intfr(v);
if (v->s.loop_filter)
ff_vc1_p_intfr_loop_filter(v);
} else {
vc1_decode_b_mb(v);
if (v->s.loop_filter)
ff_vc1_i_loop_filter(v);
}
if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {
// TODO: may need modification to handle slice coding
ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);
av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n",
get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y);
return;
}
}
memmove(v->cbp_base,
v->cbp - s->mb_stride,
sizeof(v->cbp_base[0]) * 2 * s->mb_stride);
memmove(v->ttblk_base,
v->ttblk - s->mb_stride,
sizeof(v->ttblk_base[0]) * 2 * s->mb_stride);
memmove(v->is_intra_base,
v->is_intra - s->mb_stride,
sizeof(v->is_intra_base[0]) * 2 * s->mb_stride);
if (!v->s.loop_filter)
ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16);
else if (s->mb_y)
ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
s->first_slice_line = 0;
}
if (v->s.loop_filter)
ff_mpeg_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
(s->end_mb_y << v->field_mode) - 1, ER_MB_END);
}
static void vc1_decode_skip_blocks(VC1Context *v)
{
MpegEncContext *s = &v->s;
if (!v->s.last_picture.f->data[0])
return;
ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_width - 1, s->end_mb_y - 1, ER_MB_END);
s->first_slice_line = 1;
for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
s->mb_x = 0;
init_block_index(v);
ff_update_block_index(s);
memcpy(s->dest[0], s->last_picture.f->data[0] + s->mb_y * 16 * s->linesize, s->linesize * 16);
memcpy(s->dest[1], s->last_picture.f->data[1] + s->mb_y * 8 * s->uvlinesize, s->uvlinesize * 8);
memcpy(s->dest[2], s->last_picture.f->data[2] + s->mb_y * 8 * s->uvlinesize, s->uvlinesize * 8);
ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16);
s->first_slice_line = 0;
}
s->pict_type = AV_PICTURE_TYPE_P;
}
void ff_vc1_decode_blocks(VC1Context *v)
{
v->s.esc3_level_length = 0;
if (v->x8_type) {
ff_intrax8_decode_picture(&v->x8, &v->s.current_picture,
&v->s.gb, &v->s.mb_x, &v->s.mb_y,
2 * v->pq + v->halfpq, v->pq * !v->pquantizer,
v->s.loop_filter, v->s.low_delay);
ff_er_add_slice(&v->s.er, 0, 0,
(v->s.mb_x >> 1) - 1, (v->s.mb_y >> 1) - 1,
ER_MB_END);
} else {
v->cur_blk_idx = 0;
v->left_blk_idx = -1;
v->topleft_blk_idx = 1;
v->top_blk_idx = 2;
switch (v->s.pict_type) {
case AV_PICTURE_TYPE_I:
if (v->profile == PROFILE_ADVANCED)
vc1_decode_i_blocks_adv(v);
else
vc1_decode_i_blocks(v);
break;
case AV_PICTURE_TYPE_P:
if (v->p_frame_skipped)
vc1_decode_skip_blocks(v);
else
vc1_decode_p_blocks(v);
break;
case AV_PICTURE_TYPE_B:
if (v->bi_type) {
if (v->profile == PROFILE_ADVANCED)
vc1_decode_i_blocks_adv(v);
else
vc1_decode_i_blocks(v);
} else
vc1_decode_b_blocks(v);
break;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_220_0 |
crossvul-cpp_data_good_2643_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 Notification 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 *ep,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
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="));
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
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
static const u_char *
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
{
int totlen;
uint32_t t;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
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];
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
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, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
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));
ND_PRINT((ndo," n 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;
} else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(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, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth)
{
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) {
ND_PRINT((ndo," orig=("));
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]);
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
break;
case ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN:
if (ikev1_sub_print(ndo, ISAKMP_NPTYPE_SA,
(const struct isakmp_gen *)cp, ep, phase, doi, proto,
depth) == NULL)
return NULL;
break;
default:
/* NULL is dummy */
isakmp_print(ndo, cp,
item_len - sizeof(*p) - n.spi_size,
NULL);
}
ND_PRINT((ndo,")"));
}
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, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
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);
ND_PRINT((ndo," len=%d method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (1 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < len) {
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, showdata, 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;
showdata = 0;
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;
showdata= 0;
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(3 < ndo->ndo_vflag) {
showdata = 1;
}
if ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if(showsomedata && cp < ep) {
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/good_2643_0 |
crossvul-cpp_data_bad_3412_0 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Copyright (c) 2009 by Krzysztof Helt
* Routines for control of MPU-401 in UART mode
*
* MPU-401 supports UART mode which is not capable generate transmit
* interrupts thus output is done via polling. Also, if irq < 0, then
* input is done also via polling. Do not expect good performance.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/rawmidi.h>
#include "msnd.h"
#define MSNDMIDI_MODE_BIT_INPUT 0
#define MSNDMIDI_MODE_BIT_OUTPUT 1
#define MSNDMIDI_MODE_BIT_INPUT_TRIGGER 2
#define MSNDMIDI_MODE_BIT_OUTPUT_TRIGGER 3
struct snd_msndmidi {
struct snd_msnd *dev;
unsigned long mode; /* MSNDMIDI_MODE_XXXX */
struct snd_rawmidi_substream *substream_input;
spinlock_t input_lock;
};
/*
* input/output open/close - protected by open_mutex in rawmidi.c
*/
static int snd_msndmidi_input_open(struct snd_rawmidi_substream *substream)
{
struct snd_msndmidi *mpu;
snd_printdd("snd_msndmidi_input_open()\n");
mpu = substream->rmidi->private_data;
mpu->substream_input = substream;
snd_msnd_enable_irq(mpu->dev);
snd_msnd_send_dsp_cmd(mpu->dev, HDEX_MIDI_IN_START);
set_bit(MSNDMIDI_MODE_BIT_INPUT, &mpu->mode);
return 0;
}
static int snd_msndmidi_input_close(struct snd_rawmidi_substream *substream)
{
struct snd_msndmidi *mpu;
mpu = substream->rmidi->private_data;
snd_msnd_send_dsp_cmd(mpu->dev, HDEX_MIDI_IN_STOP);
clear_bit(MSNDMIDI_MODE_BIT_INPUT, &mpu->mode);
mpu->substream_input = NULL;
snd_msnd_disable_irq(mpu->dev);
return 0;
}
static void snd_msndmidi_input_drop(struct snd_msndmidi *mpu)
{
u16 tail;
tail = readw(mpu->dev->MIDQ + JQS_wTail);
writew(tail, mpu->dev->MIDQ + JQS_wHead);
}
/*
* trigger input
*/
static void snd_msndmidi_input_trigger(struct snd_rawmidi_substream *substream,
int up)
{
unsigned long flags;
struct snd_msndmidi *mpu;
snd_printdd("snd_msndmidi_input_trigger(, %i)\n", up);
mpu = substream->rmidi->private_data;
spin_lock_irqsave(&mpu->input_lock, flags);
if (up) {
if (!test_and_set_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER,
&mpu->mode))
snd_msndmidi_input_drop(mpu);
} else {
clear_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER, &mpu->mode);
}
spin_unlock_irqrestore(&mpu->input_lock, flags);
if (up)
snd_msndmidi_input_read(mpu);
}
void snd_msndmidi_input_read(void *mpuv)
{
unsigned long flags;
struct snd_msndmidi *mpu = mpuv;
void *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF;
spin_lock_irqsave(&mpu->input_lock, flags);
while (readw(mpu->dev->MIDQ + JQS_wTail) !=
readw(mpu->dev->MIDQ + JQS_wHead)) {
u16 wTmp, val;
val = readw(pwMIDQData + 2 * readw(mpu->dev->MIDQ + JQS_wHead));
if (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER,
&mpu->mode))
snd_rawmidi_receive(mpu->substream_input,
(unsigned char *)&val, 1);
wTmp = readw(mpu->dev->MIDQ + JQS_wHead) + 1;
if (wTmp > readw(mpu->dev->MIDQ + JQS_wSize))
writew(0, mpu->dev->MIDQ + JQS_wHead);
else
writew(wTmp, mpu->dev->MIDQ + JQS_wHead);
}
spin_unlock_irqrestore(&mpu->input_lock, flags);
}
EXPORT_SYMBOL(snd_msndmidi_input_read);
static const struct snd_rawmidi_ops snd_msndmidi_input = {
.open = snd_msndmidi_input_open,
.close = snd_msndmidi_input_close,
.trigger = snd_msndmidi_input_trigger,
};
static void snd_msndmidi_free(struct snd_rawmidi *rmidi)
{
struct snd_msndmidi *mpu = rmidi->private_data;
kfree(mpu);
}
int snd_msndmidi_new(struct snd_card *card, int device)
{
struct snd_msnd *chip = card->private_data;
struct snd_msndmidi *mpu;
struct snd_rawmidi *rmidi;
int err;
err = snd_rawmidi_new(card, "MSND-MIDI", device, 1, 1, &rmidi);
if (err < 0)
return err;
mpu = kzalloc(sizeof(*mpu), GFP_KERNEL);
if (mpu == NULL) {
snd_device_free(card, rmidi);
return -ENOMEM;
}
mpu->dev = chip;
chip->msndmidi_mpu = mpu;
rmidi->private_data = mpu;
rmidi->private_free = snd_msndmidi_free;
spin_lock_init(&mpu->input_lock);
strcpy(rmidi->name, "MSND MIDI");
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
&snd_msndmidi_input);
rmidi->info_flags |= SNDRV_RAWMIDI_INFO_INPUT;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3412_0 |
crossvul-cpp_data_good_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);
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/good_2644_1 |
crossvul-cpp_data_good_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)
goto trunc;
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)
goto trunc;
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
if (length < 1)
goto trunc;
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; i < length && *data; 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/good_2708_0 |
crossvul-cpp_data_bad_2714_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.
*
* 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_TCHECK_24BITS(p + 2);
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_TCHECK_16BITS(p + 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_TCHECK_32BITS(p + 2);
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_TCHECK_16BITS(p + 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_TCHECK_16BITS(p+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_TCHECK_32BITS(p + 2);
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_TCHECK_16BITS(p + 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_TCHECK_16BITS(p + 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_TCHECK_16BITS(p+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_TCHECK(p[2]);
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_TCHECK(p[3]);
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_TCHECK(p[3]);
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_TCHECK_32BITS(p + 2);
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);
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_2714_0 |
crossvul-cpp_data_bad_4792_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(unsigned char)); /* 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_4792_0 |
crossvul-cpp_data_bad_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);
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);
return(MagickFalse);
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r m a t M a g i c k C a p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatMagickCaption() formats a caption so that it fits within the image
% width. It returns the number of lines in the formatted caption.
%
% The format of the FormatMagickCaption method is:
%
% ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
% const MagickBooleanType split,TypeMetric *metrics,char **caption,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o draw_info: the draw info.
%
% o split: when no convenient line breaks-- insert newline.
%
% o metrics: Return the font metrics in this structure.
%
% o caption: the caption.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info,
const MagickBooleanType split,TypeMetric *metrics,char **caption,
ExceptionInfo *exception)
{
MagickBooleanType
status;
register char
*p,
*q,
*s;
register ssize_t
i;
size_t
width;
ssize_t
n;
q=draw_info->text;
s=(char *) NULL;
for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
{
if (IsUTFSpace(GetUTFCode(p)) != MagickFalse)
s=p;
if (GetUTFCode(p) == '\n')
{
q=draw_info->text;
continue;
}
for (i=0; i < (ssize_t) GetUTFOctets(p); i++)
*q++=(*(p+i));
*q='\0';
status=GetTypeMetrics(image,draw_info,metrics,exception);
if (status == MagickFalse)
break;
width=(size_t) floor(metrics->width+draw_info->stroke_width+0.5);
if (width <= image->columns)
continue;
if (s != (char *) NULL)
{
*s='\n';
p=s;
}
else
if (split != MagickFalse)
{
/*
No convenient line breaks-- insert newline.
*/
n=p-(*caption);
if ((n > 0) && ((*caption)[n-1] != '\n'))
{
char
*target;
target=AcquireString(*caption);
CopyMagickString(target,*caption,n+1);
ConcatenateMagickString(target,"\n",strlen(*caption)+1);
ConcatenateMagickString(target,p,strlen(*caption)+2);
(void) DestroyString(*caption);
*caption=target;
p=(*caption)+n;
}
}
q=draw_info->text;
s=(char *) NULL;
}
n=0;
for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p))
if (GetUTFCode(p) == '\n')
n++;
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t M u l t i l i n e T y p e M e t r i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMultilineTypeMetrics() returns the following information for the
% specified font and text:
%
% character width
% character height
% ascender
% descender
% text width
% text height
% maximum horizontal advance
% bounds: x1
% bounds: y1
% bounds: x2
% bounds: y2
% origin: x
% origin: y
% underline position
% underline thickness
%
% This method is like GetTypeMetrics() but it returns the maximum text width
% and height for multiple lines of text.
%
% The format of the GetMultilineTypeMetrics method is:
%
% MagickBooleanType GetMultilineTypeMetrics(Image *image,
% const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o metrics: Return the font metrics in this structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetMultilineTypeMetrics(Image *image,
const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception)
{
char
**textlist;
DrawInfo
*annotate_info;
MagickBooleanType
status;
register ssize_t
i;
size_t
height,
count;
TypeMetric
extent;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->text != (char *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (*draw_info->text == '\0')
return(MagickFalse);
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->text=DestroyString(annotate_info->text);
/*
Convert newlines to multiple lines of text.
*/
textlist=StringToStrings(draw_info->text,&count);
if (textlist == (char **) NULL)
return(MagickFalse);
annotate_info->render=MagickFalse;
annotate_info->direction=UndefinedDirection;
(void) memset(metrics,0,sizeof(*metrics));
(void) memset(&extent,0,sizeof(extent));
/*
Find the widest of the text lines.
*/
annotate_info->text=textlist[0];
status=GetTypeMetrics(image,annotate_info,&extent,exception);
*metrics=extent;
height=(count*(size_t) (metrics->ascent-metrics->descent+
0.5)+(count-1)*draw_info->interline_spacing);
if (AcquireMagickResource(HeightResource,height) == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"WidthOrHeightExceedsLimit","`%s'",image->filename);
status=MagickFalse;
}
else
{
for (i=1; i < (ssize_t) count; i++)
{
annotate_info->text=textlist[i];
status=GetTypeMetrics(image,annotate_info,&extent,exception);
if (status == MagickFalse)
break;
if (extent.width > metrics->width)
*metrics=extent;
if (AcquireMagickResource(WidthResource,extent.width) == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"WidthOrHeightExceedsLimit","`%s'",image->filename);
status=MagickFalse;
break;
}
}
metrics->height=(double) height;
}
/*
Relinquish resources.
*/
annotate_info->text=(char *) NULL;
annotate_info=DestroyDrawInfo(annotate_info);
for (i=0; i < (ssize_t) count; i++)
textlist[i]=DestroyString(textlist[i]);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T y p e M e t r i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetTypeMetrics() returns the following information for the specified font
% and text:
%
% character width
% character height
% ascender
% descender
% text width
% text height
% maximum horizontal advance
% bounds: x1
% bounds: y1
% bounds: x2
% bounds: y2
% origin: x
% origin: y
% underline position
% underline thickness
%
% The format of the GetTypeMetrics method is:
%
% MagickBooleanType GetTypeMetrics(Image *image,const DrawInfo *draw_info,
% TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o metrics: Return the font metrics in this structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetTypeMetrics(Image *image,
const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception)
{
DrawInfo
*annotate_info;
MagickBooleanType
status;
PointInfo
offset;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->text != (char *) NULL);
assert(draw_info->signature == MagickCoreSignature);
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->render=MagickFalse;
annotate_info->direction=UndefinedDirection;
(void) memset(metrics,0,sizeof(*metrics));
offset.x=0.0;
offset.y=0.0;
status=RenderType(image,annotate_info,&offset,metrics,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Metrics: text: %s; "
"width: %g; height: %g; ascent: %g; descent: %g; max advance: %g; "
"bounds: %g,%g %g,%g; origin: %g,%g; pixels per em: %g,%g; "
"underline position: %g; underline thickness: %g",annotate_info->text,
metrics->width,metrics->height,metrics->ascent,metrics->descent,
metrics->max_advance,metrics->bounds.x1,metrics->bounds.y1,
metrics->bounds.x2,metrics->bounds.y2,metrics->origin.x,metrics->origin.y,
metrics->pixels_per_em.x,metrics->pixels_per_em.y,
metrics->underline_position,metrics->underline_thickness);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderType() renders text on the image. It also returns the bounding box of
% the text relative to the image.
%
% The format of the RenderType method is:
%
% MagickBooleanType RenderType(Image *image,DrawInfo *draw_info,
% const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType RenderType(Image *image,const DrawInfo *draw_info,
const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
{
const TypeInfo
*type_info;
DrawInfo
*annotate_info;
MagickBooleanType
status;
type_info=(const TypeInfo *) NULL;
if (draw_info->font != (char *) NULL)
{
if (*draw_info->font == '@')
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics,exception);
return(status);
}
if (*draw_info->font == '-')
return(RenderX11(image,draw_info,offset,metrics,exception));
if (*draw_info->font == '^')
return(RenderPostscript(image,draw_info,offset,metrics,exception));
if (IsPathAccessible(draw_info->font) != MagickFalse)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics,exception);
return(status);
}
type_info=GetTypeInfo(draw_info->font,exception);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"UnableToReadFont","`%s'",draw_info->font);
}
if ((type_info == (const TypeInfo *) NULL) &&
(draw_info->family != (const char *) NULL))
{
type_info=GetTypeInfoByFamily(draw_info->family,draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
{
char
**family;
int
number_families;
register ssize_t
i;
/*
Parse font family list.
*/
family=StringToArgv(draw_info->family,&number_families);
for (i=1; i < (ssize_t) number_families; i++)
{
type_info=GetTypeInfoByFamily(family[i],draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info != (const TypeInfo *) NULL)
break;
}
for (i=0; i < (ssize_t) number_families; i++)
family[i]=DestroyString(family[i]);
family=(char **) RelinquishMagickMemory(family);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"UnableToReadFont","`%s'",draw_info->family);
}
}
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Arial",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Helvetica",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Century Schoolbook",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Sans",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily((const char *) NULL,draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfo("*",exception);
if (type_info == (const TypeInfo *) NULL)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,metrics,
exception);
return(status);
}
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->face=type_info->face;
if (type_info->metrics != (char *) NULL)
(void) CloneString(&annotate_info->metrics,type_info->metrics);
if (type_info->glyphs != (char *) NULL)
(void) CloneString(&annotate_info->font,type_info->glyphs);
status=RenderFreetype(image,annotate_info,type_info->encoding,offset,metrics,
exception);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e n d e r F r e e t y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RenderFreetype() renders text on the image with a Truetype font. It also
% returns the bounding box of the text relative to the image.
%
% The format of the RenderFreetype method is:
%
% MagickBooleanType RenderFreetype(Image *image,DrawInfo *draw_info,
% const char *encoding,const PointInfo *offset,TypeMetric *metrics,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o encoding: the font encoding.
%
% o offset: (x,y) location of text relative to image.
%
% o metrics: bounding box of text.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FREETYPE_DELEGATE)
static size_t ComplexTextLayout(const Image *image,const DrawInfo *draw_info,
const char *text,const size_t length,const FT_Face face,const FT_Int32 flags,
GraphemeInfo **grapheme,ExceptionInfo *exception)
{
#if defined(MAGICKCORE_RAQM_DELEGATE)
const char
*features;
raqm_t
*rq;
raqm_glyph_t
*glyphs;
register ssize_t
i;
size_t
extent;
extent=0;
rq=raqm_create();
if (rq == (raqm_t *) NULL)
goto cleanup;
if (raqm_set_text_utf8(rq,text,length) == 0)
goto cleanup;
if (raqm_set_par_direction(rq,(raqm_direction_t) draw_info->direction) == 0)
goto cleanup;
if (raqm_set_freetype_face(rq,face) == 0)
goto cleanup;
features=GetImageProperty(image,"type:features",exception);
if (features != (const char *) NULL)
{
char
breaker,
quote,
*token;
int
next,
status_token;
TokenInfo
*token_info;
next=0;
token_info=AcquireTokenInfo();
token=AcquireString("");
status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0',
&breaker,&next,"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/bad_949_0 |
crossvul-cpp_data_bad_351_3 | /*
* card-cac.c: Support for CAC 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,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
* Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
* Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
* Copyright (C) 2016 - 2018, Red Hat, Inc.
*
* CAC driver author: Robert Relyea <rrelyea@redhat.com>
* Further work: Jakub Jelen <jjelen@redhat.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 "simpletlv.h"
#include "cardctl.h"
#ifdef ENABLE_ZLIB
#include "compression.h"
#endif
#include "iso7816.h"
#define CAC_MAX_SIZE 4096 /* arbitrary, just needs to be 'large enough' */
/*
* CAC hardware and APDU constants
*/
#define CAC_MAX_CHUNK_SIZE 240
#define CAC_INS_SIGN_DECRYPT 0x42 /* A crypto operation */
#define CAC_INS_READ_FILE 0x52 /* read a TL or V file */
#define CAC_INS_GET_ACR 0x4c
#define CAC_INS_GET_PROPERTIES 0x56
#define CAC_P1_STEP 0x80
#define CAC_P1_FINAL 0x00
#define CAC_FILE_TAG 1
#define CAC_FILE_VALUE 2
/* TAGS in a TL file */
#define CAC_TAG_CERTIFICATE 0x70
#define CAC_TAG_CERTINFO 0x71
#define CAC_TAG_MSCUID 0x72
#define CAC_TAG_CUID 0xF0
#define CAC_TAG_CC_VERSION_NUMBER 0xF1
#define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2
#define CAC_TAG_CARDURL 0xF3
#define CAC_TAG_PKCS15 0xF4
#define CAC_TAG_ACCESS_CONTROL 0xF6
#define CAC_TAG_DATA_MODEL 0xF5
#define CAC_TAG_CARD_APDU 0xF7
#define CAC_TAG_REDIRECTION 0xFA
#define CAC_TAG_CAPABILITY_TUPLES 0xFB
#define CAC_TAG_STATUS_TUPLES 0xFC
#define CAC_TAG_NEXT_CCC 0xFD
#define CAC_TAG_ERROR_CODES 0xFE
#define CAC_TAG_APPLET_FAMILY 0x01
#define CAC_TAG_NUMBER_APPLETS 0x94
#define CAC_TAG_APPLET_ENTRY 0x93
#define CAC_TAG_APPLET_AID 0x92
#define CAC_TAG_APPLET_INFORMATION 0x01
#define CAC_TAG_NUMBER_OF_OBJECTS 0x40
#define CAC_TAG_TV_BUFFER 0x50
#define CAC_TAG_PKI_OBJECT 0x51
#define CAC_TAG_OBJECT_ID 0x41
#define CAC_TAG_BUFFER_PROPERTIES 0x42
#define CAC_TAG_PKI_PROPERTIES 0x43
#define CAC_APP_TYPE_GENERAL 0x01
#define CAC_APP_TYPE_SKI 0x02
#define CAC_APP_TYPE_PKI 0x04
#define CAC_ACR_ACR 0x00
#define CAC_ACR_APPLET_OBJECT 0x10
#define CAC_ACR_AMP 0x20
#define CAC_ACR_SERVICE 0x21
/* hardware data structures (returned in the CCC) */
/* part of the card_url */
typedef struct cac_access_profile {
u8 GCACR_listID;
u8 GCACR_readTagListACRID;
u8 GCACR_updatevalueACRID;
u8 GCACR_readvalueACRID;
u8 GCACR_createACRID;
u8 GCACR_deleteACRID;
u8 CryptoACR_listID;
u8 CryptoACR_getChallengeACRID;
u8 CryptoACR_internalAuthenicateACRID;
u8 CryptoACR_pkiComputeACRID;
u8 CryptoACR_readTagListACRID;
u8 CryptoACR_updatevalueACRID;
u8 CryptoACR_readvalueACRID;
u8 CryptoACR_createACRID;
u8 CryptoACR_deleteACRID;
} cac_access_profile_t;
/* part of the card url */
typedef struct cac_access_key_info {
u8 keyFileID[2];
u8 keynumber;
} cac_access_key_info_t;
typedef struct cac_card_url {
u8 rid[5];
u8 cardApplicationType;
u8 objectID[2];
u8 applicationID[2];
cac_access_profile_t accessProfile;
u8 pinID; /* not used for VM cards */
cac_access_key_info_t accessKeyInfo; /* not used for VM cards */
u8 keyCryptoAlgorithm; /* not used for VM cards */
} cac_card_url_t;
typedef struct cac_cuid {
u8 gsc_rid[5];
u8 manufacturer_id;
u8 card_type;
u8 card_id;
} cac_cuid_t;
/* data structures to store meta data about CAC objects */
typedef struct cac_object {
const char *name;
int fd;
sc_path_t path;
} cac_object_t;
#define CAC_MAX_OBJECTS 16
typedef struct {
/* OID has two bytes */
unsigned char oid[2];
/* Format is NOT SimpleTLV? */
unsigned char simpletlv;
/* Is certificate object and private key is initialized */
unsigned char privatekey;
} cac_properties_object_t;
typedef struct {
unsigned int num_objects;
cac_properties_object_t objects[CAC_MAX_OBJECTS];
} cac_properties_t;
/*
* Flags for Current Selected Object Type
* CAC files are TLV files, with TL and V separated. For generic
* containers we reintegrate the TL anv V portions into a single
* file to read. Certs are also TLV files, but pkcs15 wants the
* actual certificate. At select time we know the patch which tells
* us what time of files we want to read. We remember that type
* so that read_binary can do the appropriate processing.
*/
#define CAC_OBJECT_TYPE_CERT 1
#define CAC_OBJECT_TYPE_TLV_FILE 4
#define CAC_OBJECT_TYPE_GENERIC 5
/*
* CAC private data per card state
*/
typedef struct cac_private_data {
int object_type; /* select set this so we know how to read the file */
int cert_next; /* index number for the next certificate found in the list */
u8 *cache_buf; /* cached version of the currently selected file */
size_t cache_buf_len; /* length of the cached selected file */
int cached; /* is the cached selected file valid */
cac_cuid_t cuid; /* card unique ID from the CCC */
u8 *cac_id; /* card serial number */
size_t cac_id_len; /* card serial number len */
list_t pki_list; /* list of pki containers */
cac_object_t *pki_current; /* current pki object _ctl function */
list_t general_list; /* list of general containers */
cac_object_t *general_current; /* current object for _ctl function */
sc_path_t *aca_path; /* ACA path to be selected before pin verification */
} cac_private_data_t;
#define CAC_DATA(card) ((cac_private_data_t*)card->drv_data)
int cac_list_compare_path(const void *a, const void *b)
{
if (a == NULL || b == NULL)
return 1;
return memcmp( &((cac_object_t *) a)->path,
&((cac_object_t *) b)->path, sizeof(sc_path_t));
}
/* For SimCList autocopy, we need to know the size of the data elements */
size_t cac_list_meter(const void *el) {
return sizeof(cac_object_t);
}
static cac_private_data_t *cac_new_private_data(void)
{
cac_private_data_t *priv;
priv = calloc(1, sizeof(cac_private_data_t));
if (!priv)
return NULL;
list_init(&priv->pki_list);
list_attributes_comparator(&priv->pki_list, cac_list_compare_path);
list_attributes_copy(&priv->pki_list, cac_list_meter, 1);
list_init(&priv->general_list);
list_attributes_comparator(&priv->general_list, cac_list_compare_path);
list_attributes_copy(&priv->general_list, cac_list_meter, 1);
/* set other fields as appropriate */
return priv;
}
static void cac_free_private_data(cac_private_data_t *priv)
{
free(priv->cac_id);
free(priv->cache_buf);
free(priv->aca_path);
list_destroy(&priv->pki_list);
list_destroy(&priv->general_list);
free(priv);
return;
}
static int cac_add_object_to_list(list_t *list, const cac_object_t *object)
{
if (list_append(list, object) < 0)
return SC_ERROR_UNKNOWN;
return SC_SUCCESS;
}
/*
* Set up the normal CAC paths
*/
#define CAC_TO_AID(x) x, sizeof(x)-1
#define CAC_2_RID "\xA0\x00\x00\x01\x16"
#define CAC_1_RID "\xA0\x00\x00\x00\x79"
static const sc_path_t cac_ACA_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x10\x00") }
};
static const sc_path_t cac_CCC_Path = {
"", 0,
0,0,SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_2_RID "\xDB\x00") }
};
#define MAX_CAC_SLOTS 16 /* Maximum number of slots is 16 now */
/* default certificate labels for the CAC card */
static const char *cac_labels[MAX_CAC_SLOTS] = {
"CAC ID Certificate",
"CAC Email Signature Certificate",
"CAC Email Encryption Certificate",
"CAC Cert 4",
"CAC Cert 5",
"CAC Cert 6",
"CAC Cert 7",
"CAC Cert 8",
"CAC Cert 9",
"CAC Cert 10",
"CAC Cert 11",
"CAC Cert 12",
"CAC Cert 13",
"CAC Cert 14",
"CAC Cert 15",
"CAC Cert 16"
};
/* template for a CAC pki object */
static const cac_object_t cac_cac_pki_obj = {
"CAC Certificate", 0x0, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x01\x00") } }
};
/* template for emulated cuid */
static const cac_cuid_t cac_cac_cuid = {
{ 0xa0, 0x00, 0x00, 0x00, 0x79 },
2, 2, 0
};
/*
* CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0.
* doubles as a source for CAC-2 labels.
*/
static const cac_object_t cac_objects[] = {
{ "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x00") }}},
{ "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x01") }}},
{ "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x02") }}},
{ "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\x03") }}},
{ "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFD") }}},
{ "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
{ CAC_TO_AID(CAC_1_RID "\x02\xFE") }}},
};
static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]);
/*
* use the object id to find our object info on the object in our CAC-1 list
*/
static const cac_object_t *cac_find_obj_by_id(unsigned short object_id)
{
int i;
for (i = 0; i < cac_object_count; i++) {
if (cac_objects[i].fd == object_id) {
return &cac_objects[i];
}
}
return NULL;
}
/*
* Lookup the path in the pki list to see if it is a cert path
*/
static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path)
{
cac_object_t test_obj;
test_obj.path = *in_path;
test_obj.path.index = 0;
test_obj.path.count = 0;
return (list_contains(&priv->pki_list, &test_obj) != 0);
}
/*
* Send a command and receive data.
*
* 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.
*
* modelled after a similar function in card-piv.c
*/
static int cac_apdu_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[CAC_MAX_SIZE];
u8 *rbuf;
size_t rbuflen;
unsigned int apdu_case = SC_APDU_CASE_1;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
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;
}
if (recvbuf) {
if (sendbuf)
apdu_case = SC_APDU_CASE_4_SHORT;
else
apdu_case = SC_APDU_CASE_2_SHORT;
} else if (sendbuf)
apdu_case = SC_APDU_CASE_3_SHORT;
sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
apdu.lc = sendbuflen;
apdu.datalen = sendbuflen;
apdu.data = sendbuf;
if (recvbuf) {
apdu.resp = rbuf;
apdu.le = (rbuflen > 255) ? 255 : rbuflen;
apdu.resplen = rbuflen;
} else {
apdu.resp = rbuf;
apdu.le = 0;
apdu.resplen = 0;
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"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_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"result 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_debug(card->ctx, SC_LOG_DEBUG_NORMAL,"Transmit failed");
goto err;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Card returned error ");
goto err;
}
if (recvbuflen) {
if (recvbuf && *recvbuf == NULL) {
*recvbuf = malloc(apdu.resplen);
if (*recvbuf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto err;
}
memcpy(*recvbuf, rbuf, apdu.resplen);
}
*recvbuflen = apdu.resplen;
r = *recvbuflen;
}
err:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Get ACR of currently ACA applet identified by the acr_type
* 5.3.3.5 Get ACR APDU
*/
static int
cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len)
{
u8 *out = NULL;
/* XXX assuming it will not be longer than 255 B */
size_t len = 256;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* for simplicity we support only ACR without arguments now */
if (acr_type != 0x00 && acr_type != 0x10
&& acr_type != 0x20 && acr_type != 0x21) {
return SC_ERROR_INVALID_ARGUMENTS;
}
r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out);
*out_len = len;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_buf = NULL;
*out_len = 0;
return r;
}
/*
* Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file
*/
#define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff)
#define LOW_BYTE_OF_SHORT(x) ((x) & 0xff)
static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len)
{
u8 params[2];
u8 count[2];
u8 *out = NULL;
u8 *out_ptr;
size_t offset = 0;
size_t size = 0;
size_t left = 0;
size_t len;
int r;
params[0] = file_type;
params[1] = 2;
/* get the size */
len = sizeof(count);
out_ptr = count;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, ¶ms[0], sizeof(params), &out_ptr, &len);
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0)
goto fail;
left = size = lebytes2ushort(count);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)",
len, out_ptr, &count, count[0], count[1], size, size);
out = out_ptr = malloc(size);
if (out == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto fail;
}
for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) {
len = MIN(left, CAC_MAX_CHUNK_SIZE);
params[1] = len;
r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset),
¶ms[0], sizeof(params), &out_ptr, &len);
/* if there is no data, assume there is no file */
if (len == 0) {
r = SC_ERROR_FILE_NOT_FOUND;
}
if (r < 0) {
goto fail;
}
}
*out_len = size;
*out_buf = out;
return SC_SUCCESS;
fail:
if (out)
free(out);
*out_len = 0;
return r;
}
/*
* 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 cac_read_binary(sc_card_t *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
cac_private_data_t * priv = CAC_DATA(card);
int r = 0;
u8 *tl = NULL, *val = NULL;
u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start;
u8 *cert_ptr;
size_t tl_len, val_len, tlv_len;
size_t len, tl_head_len, cert_len;
u8 cert_type, tag;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* if we didn't return it all last time, return the remainder */
if (priv->cached) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (idx > priv->cache_buf_len) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED);
}
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len);
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
priv->cache_buf_len = 0;
}
if (priv->object_type <= 0)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0) {
goto done;
}
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
switch (priv->object_type) {
case CAC_OBJECT_TYPE_TLV_FILE:
tlv_len = tl_len + val_len;
priv->cache_buf = malloc(tlv_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = tlv_len;
for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
tl_len >= 2 && tlv_len > 0;
val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
/* get the tag and the length */
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = (tl_ptr - tl_start);
sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
tlv_len -= tl_head_len;
tl_len -= tl_head_len;
/* don't crash on bad data */
if (val_len < len) {
len = val_len;
}
/* if we run out of return space, truncate */
if (tlv_len < len) {
len = tlv_len;
}
memcpy(tlv_ptr, val_ptr, len);
}
break;
case CAC_OBJECT_TYPE_CERT:
/* read file */
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
" obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
val_len, val_len);
cert_len = 0;
cert_ptr = NULL;
cert_type = 0;
for (tl_ptr = tl, val_ptr=val; tl_len >= 2;
val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = tl_ptr - tl_start;
if (tag == CAC_TAG_CERTIFICATE) {
cert_len = len;
cert_ptr = val_ptr;
}
if (tag == CAC_TAG_CERTINFO) {
if ((len >= 1) && (val_len >=1)) {
cert_type = *val_ptr;
}
}
if (tag == CAC_TAG_MSCUID) {
sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
}
if ((val_len < len) || (tl_len < tl_head_len)) {
break;
}
}
/* if the info byte is 1, then the cert is compressed, decompress it */
if ((cert_type & 0x3) == 1) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len,
cert_ptr, cert_len, COMPRESSION_AUTO);
#else
sc_log(card->ctx, "CAC compression not supported, no zlib");
r = SC_ERROR_NOT_SUPPORTED;
#endif
if (r)
goto done;
} else if (cert_len > 0) {
priv->cache_buf = malloc(cert_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = cert_len;
memcpy(priv->cache_buf, cert_ptr, cert_len);
} else {
sc_log(card->ctx, "Can't read zero-length certificate");
goto done;
}
break;
case CAC_OBJECT_TYPE_GENERIC:
/* TODO
* We have some two buffers in unknown encoding that we
* need to present in PKCS#15 layer.
*/
default:
/* Unknown object type */
sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
r = SC_ERROR_INTERNAL;
goto done;
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
priv->cached = 1;
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
r = len;
done:
if (tl)
free(tl);
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/* CAC driver is read only */
static int cac_write_binary(sc_card_t *card, unsigned int idx,
const u8 *buf, size_t count, unsigned long flags)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
/* initialize getting a list and return the number of elements in the list */
static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp)
{
*countp = list_size(list);
list_iterator_start(list);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
/* finalize the list iterator */
static int cac_final_iterator(list_t *list)
{
list_iterator_stop(list);
return SC_SUCCESS;
}
/* fill in the obj_info for the current object on the list and advance to the next object */
static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info)
{
memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t));
if (*entry == NULL) {
return SC_ERROR_FILE_END_REACHED;
}
obj_info->path = (*entry)->path;
obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */
obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff;
obj_info->id.value[1] = (*entry)->fd & 0xff;
obj_info->id.len = 2;
strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1);
*entry = list_iterator_next(list);
return SC_SUCCESS;
}
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (card->serialnr.len) {
*serial = card->serialnr;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
if (priv->cac_id_len) {
serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
memcpy(serial->value, priv->cac_id, priv->cac_id_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND);
}
static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (priv->aca_path) {
*path = *priv->aca_path;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
cac_private_data_t * priv = CAC_DATA(card);
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_CAC_GET_ACA_PATH:
return cac_get_ACA_path(card, (sc_path_t *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS:
return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr);
case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS:
return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT:
return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT:
return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr);
case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS:
return cac_final_iterator(&priv->general_list);
case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS:
return cac_final_iterator(&priv->pki_list);
}
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
{
/* CAC requires 8 byte response */
u8 rbuf[8];
u8 *rbufp = &rbuf[0];
size_t out_len = sizeof rbuf;
int r;
LOG_FUNC_CALLED(card->ctx);
r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len);
LOG_TEST_RET(card->ctx, r, "Could not get challenge");
if (len < out_len) {
out_len = len;
}
memcpy(rnd, rbuf, out_len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, (int) out_len);
}
static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
env->flags, env->operation, env->algorithm,
env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
env->key_ref_len);
if (env->algorithm != SC_ALGORITHM_RSA) {
r = SC_ERROR_NO_CARD_SUPPORT;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int cac_restore_security_env(sc_card_t *card, int se_num)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_rsa_op(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
u8 *outp, *rbuf;
size_t rbuflen, outplen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
datalen, outlen);
outp = out;
outplen = outlen;
/* Not strictly necessary. This code requires the caller to have selected the correct PKI container
* and authenticated to that container with the verifyPin command... All of this under the reader lock.
* The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just
* different sets of APDU's that need to be called), so this call is really a little bit of paranoia */
r = sc_lock(card);
if (r != SC_SUCCESS)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
rbuf = NULL;
rbuflen = 0;
for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) {
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP, 0,
data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen);
if (r < 0) {
break;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
outp += n;
outplen -= n;
}
free(rbuf);
rbuf = NULL;
rbuflen = 0;
}
if (r < 0) {
goto err;
}
rbuf = NULL;
rbuflen = 0;
r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen);
if (r < 0) {
goto err;
}
if (rbuflen != 0) {
int n = MIN(rbuflen, outplen);
memcpy(outp,rbuf, n);
/*outp += n; unused */
outplen -= n;
}
free(rbuf);
rbuf = NULL;
r = outlen-outplen;
err:
sc_unlock(card);
if (r < 0) {
sc_mem_clear(out, outlen);
}
if (rbuf) {
free(rbuf);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int cac_compute_signature(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, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_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, cac_rsa_op(card, data, datalen, out, outlen));
}
static int cac_parse_properties_object(sc_card_t *card, u8 type,
u8 *data, size_t data_len, cac_properties_object_t *object)
{
size_t len;
u8 *val, *val_end, tag;
int parsed = 0;
if (data_len < 11)
return -1;
/* Initilize: non-PKI applet */
object->privatekey = 0;
val = data;
val_end = data + data_len;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_OBJECT_ID:
if (len != 2) {
sc_log(card->ctx, "TAG: Object ID: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]);
memcpy(&object->oid, val, 2);
parsed++;
break;
case CAC_TAG_BUFFER_PROPERTIES:
if (len != 5) {
sc_log(card->ctx, "TAG: Buffer Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* First byte is "Type of Tag Supported" */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Buffer Properties: Type of Tag Supported = 0x%02x",
val[0]);
object->simpletlv = val[0];
parsed++;
break;
case CAC_TAG_PKI_PROPERTIES:
/* 4th byte is "Private Key Initialized" */
if (len != 4) {
sc_log(card->ctx, "TAG: PKI Properties: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
if (type != CAC_TAG_PKI_OBJECT) {
sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object");
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Properties: Private Key Initialized = 0x%02x",
val[2]);
object->privatekey = val[2];
parsed++;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)",tag );
break;
}
}
if (parsed < 2)
return SC_ERROR_INVALID_DATA;
return SC_SUCCESS;
}
static int cac_get_properties(sc_card_t *card, cac_properties_t *prop)
{
u8 *rbuf = NULL;
size_t rbuflen = 0, len;
u8 *val, *val_end, tag;
size_t i = 0;
int r;
prop->num_objects = 0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0,
&rbuf, &rbuflen);
if (r < 0)
return r;
val = rbuf;
val_end = val + rbuflen;
for (; val < val_end; val += len) {
/* get the tag and the length */
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_INFORMATION:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%0x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_OF_OBJECTS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num objects: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num objects = %hhd", *val);
/* make sure we do not overrun buffer */
prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS);
break;
case CAC_TAG_TV_BUFFER:
if (len != 17) {
sc_log(card->ctx, "TAG: TV Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
case CAC_TAG_PKI_OBJECT:
if (len != 17) {
sc_log(card->ctx, "TAG: PKI Object: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
if (i >= CAC_MAX_OBJECTS) {
free(rbuf);
return SC_SUCCESS;
}
if (cac_parse_properties_object(card, tag, val, len,
&prop->objects[i]) == SC_SUCCESS)
i++;
break;
default:
/* ignore tags we don't understand */
sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%"
SC_FORMAT_LEN_SIZE_T"u", tag, len);
break;
}
}
free(rbuf);
/* sanity */
if (i != prop->num_objects)
sc_log(card->ctx, "The announced number of objects (%u) "
"did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)",
prop->num_objects, i);
prop->num_objects = i;
return SC_SUCCESS;
}
/*
* CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more
* of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead
* of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS
* if it doesn't like anything about the select, so we always 'request' FCI for CAC1
*
* The rest is just copied from iso7816_select_file
*/
static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out, int type)
{
struct sc_context *ctx;
struct sc_apdu apdu;
unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
int r, pathlen, pathtype;
struct sc_file *file = NULL;
cac_private_data_t * priv = CAC_DATA(card);
assert(card != NULL && in_path != NULL);
ctx = card->ctx;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
pathtype = in_path->type;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
in_path->aid.value[0], in_path->aid.value[1],
in_path->aid.value[2], in_path->aid.value[3],
in_path->aid.value[4], in_path->aid.value[5],
in_path->aid.value[6], in_path->aid.len, in_path->value[0],
in_path->value[1], in_path->value[2], in_path->value[3],
in_path->len, in_path->type, in_path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
file_out, in_path->index, in_path->count);
/* Sigh, sc_key_select expects paths to keys to have specific formats. There is no override.
* we have to add some bytes to the path to make it happy. A better fix would be to give sc_key_file
* a flag that says 'no, really this path is fine'. We only need to do this for private keys */
if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
if (pathlen > 2) {
path += 2;
pathlen -= 2;
}
}
/* CAC has multiple different type of objects that aren't PKCS #15. When we read
* them we need convert them to something PKCS #15 would understand. Find the object
* and object type here:
*/
if (priv) { /* don't record anything if we haven't been initialized yet */
priv->object_type = CAC_OBJECT_TYPE_GENERIC;
if (cac_is_cert(priv, in_path)) {
priv->object_type = CAC_OBJECT_TYPE_CERT;
}
/* forget any old cached values */
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
}
priv->cache_buf_len = 0;
priv->cached = 0;
}
if (in_path->aid.len) {
if (!pathlen) {
memcpy(path, in_path->aid.value, in_path->aid.len);
pathlen = in_path->aid.len;
pathtype = SC_PATH_TYPE_DF_NAME;
} else {
/* First, select the application */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
apdu.data = in_path->aid.value;
apdu.datalen = in_path->aid.len;
apdu.lc = in_path->aid.len;
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
switch (pathtype) {
/* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select.
* Unfortunately we'd also need to update the caching code as well. For now just
* use FILE_ID and change p1 here */
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 2;
if (pathlen != 2)
return SC_ERROR_INVALID_ARGUMENTS;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
if (file_out != NULL) {
apdu.p2 = 0; /* first record, return FCI */
}
else {
apdu.p2 = 0x0C;
}
r = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, r, "APDU transmit failed");
if (file_out == NULL) {
/* For some cards 'SELECT' can be only with request to return FCI/FCP. */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86) {
apdu.p2 = 0x00;
apdu.resplen = sizeof(buf);
if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (apdu.sw1 == 0x61)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_FUNC_RETURN(ctx, r);
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r)
LOG_FUNC_RETURN(ctx, r);
/* This needs to come after the applet selection */
if (priv && in_path->len >= 2) {
/* get applet properties to know if we can treat the
* buffer as SimpleLTV and if we have PKI applet.
*
* Do this only if we select applets for reading
* (not during driver initialization)
*/
cac_properties_t prop;
size_t i = -1;
r = cac_get_properties(card, &prop);
if (r == SC_SUCCESS) {
for (i = 0; i < prop.num_objects; i++) {
sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x",
prop.objects[i].oid[0], prop.objects[i].oid[1],
in_path->value[0], in_path->value[1]);
if (memcmp(prop.objects[i].oid,
in_path->value, 2) == 0)
break;
}
}
if (i < prop.num_objects) {
if (prop.objects[i].privatekey)
priv->object_type = CAC_OBJECT_TYPE_CERT;
else if (prop.objects[i].simpletlv == 0)
priv->object_type = CAC_OBJECT_TYPE_TLV_FILE;
}
}
/* CAC cards never return FCI, fake one */
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = *in_path;
file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
*file_out = file;
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
{
return cac_select_file_by_type(card, in_path, file_out, card->type);
}
static int cac_finish(sc_card_t *card)
{
cac_private_data_t * priv = CAC_DATA(card);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (priv) {
cac_free_private_data(priv);
}
return SC_SUCCESS;
}
/* select the Card Capabilities Container on CAC-2 */
static int cac_select_CCC(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_CCC_Path, NULL, SC_CARD_TYPE_CAC_II);
}
/* Select ACA in non-standard location */
static int cac_select_ACA(sc_card_t *card)
{
return cac_select_file_by_type(card, &cac_ACA_Path, NULL, SC_CARD_TYPE_CAC_II);
}
static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, int len)
{
if (len < 10) {
return SC_ERROR_INVALID_DATA;
}
sc_mem_clear(path, sizeof(sc_path_t));
memcpy(path->aid.value, &val->rid, sizeof(val->rid));
memcpy(&path->aid.value[5], &val->applicationID, sizeof(val->applicationID));
path->aid.len = sizeof(val->rid) + sizeof(val->applicationID);
memcpy(path->value, &val->objectID, sizeof(val->objectID));
path->len = sizeof(val->objectID);
path->type = SC_PATH_TYPE_FILE_ID;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"path->aid=%x %x %x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
path->aid.value[0], path->aid.value[1], path->aid.value[2],
path->aid.value[3], path->aid.value[4], path->aid.value[5],
path->aid.value[6], path->aid.len, path->value[0],
path->value[1], path->len, path->type, path->type);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"rid=%x %x %x %x %x len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u",
val->rid[0], val->rid[1], val->rid[2], val->rid[3],
val->rid[4], sizeof(val->rid), val->applicationID[0],
val->applicationID[1], sizeof(val->applicationID),
val->objectID[0], val->objectID[1], sizeof(val->objectID));
return SC_SUCCESS;
}
static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, u8 *aid, int aid_len)
{
cac_object_t new_object;
cac_properties_t prop;
size_t i;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Search for PKI applets (7 B). Ignore generic objects for now */
if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0
&& memcmp(aid, CAC_1_RID "\x00", 6) != 0))
return SC_SUCCESS;
sc_mem_clear(&new_object.path, sizeof(sc_path_t));
memcpy(new_object.path.aid.value, aid, aid_len);
new_object.path.aid.len = aid_len;
/* Call without OID set will just select the AID without subseqent
* OID selection, which we need to figure out just now
*/
cac_select_file_by_type(card, &new_object.path, NULL, SC_CARD_TYPE_CAC_II);
r = cac_get_properties(card, &prop);
if (r < 0)
return SC_ERROR_INTERNAL;
for (i = 0; i < prop.num_objects; i++) {
/* don't fail just because we have more certs than we can support */
if (priv->cert_next >= MAX_CAC_SLOTS)
return SC_SUCCESS;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"ACA: pki_object found, cert_next=%d (%s), privkey=%d",
priv->cert_next, cac_labels[priv->cert_next],
prop.objects[i].privatekey);
/* If the private key is not initialized, we can safely
* ignore this object here, but increase the pointer to follow
* the certificate labels
*/
if (!prop.objects[i].privatekey) {
priv->cert_next++;
continue;
}
/* OID here has always 2B */
memcpy(new_object.path.value, &prop.objects[i].oid, 2);
new_object.path.len = 2;
new_object.path.type = SC_PATH_TYPE_FILE_ID;
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
}
return SC_SUCCESS;
}
static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, int len)
{
cac_object_t new_object;
const cac_object_t *obj;
unsigned short object_id;
int r;
r = cac_path_from_cardurl(card, &new_object.path, val, len);
if (r != SC_SUCCESS) {
return r;
}
switch (val->cardApplicationType) {
case CAC_APP_TYPE_PKI:
/* we don't want to overflow the cac_label array. This test could
* go way if we create a label function that will create a unique label
* from a cert index.
*/
if (priv->cert_next >= MAX_CAC_SLOTS)
break; /* don't fail just because we have more certs than we can support */
new_object.name = cac_labels[priv->cert_next];
new_object.fd = priv->cert_next+1;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name);
cac_add_object_to_list(&priv->pki_list, &new_object);
priv->cert_next++;
break;
case CAC_APP_TYPE_GENERAL:
object_id = bebytes2ushort(val->objectID);
obj = cac_find_obj_by_id(object_id);
if (obj == NULL)
break; /* don't fail just because we don't recognize the object */
new_object.name = obj->name;
new_object.fd = 0;
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name);
cac_add_object_to_list(&priv->general_list, &new_object);
break;
case CAC_APP_TYPE_SKI:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found");
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType);
/* don't fail just because there is an unknown object in the CCC */
break;
}
return SC_SUCCESS;
}
static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len)
{
size_t card_id_len;
if (len < sizeof(cac_cuid_t)) {
return SC_ERROR_INVALID_DATA;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid)));
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type);
card_id_len = len - (&val->card_id - (u8 *)val);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)",
sc_dump_hex(&val->card_id, card_id_len),
card_id_len);
priv->cuid = *val;
priv->cac_id = malloc(card_id_len);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
memcpy(priv->cac_id, &val->card_id, card_id_len);
priv->cac_id_len = card_id_len;
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv);
static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, u8 *tl,
size_t tl_len, u8 *val, size_t val_len)
{
size_t len = 0;
u8 *tl_end = tl + tl_len;
u8 *val_end = val + val_len;
sc_path_t new_path;
int r;
for (; (tl < tl_end) && (val< val_end); val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_CUID:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID");
r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len);
if (r < 0)
return r;
break;
case CAC_TAG_CC_VERSION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: CC Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: CC Version = 0x%02x", *val);
break;
case CAC_TAG_GRAMMAR_VERION_NUMBER:
if (len != 1) {
sc_log(card->ctx, "TAG: Grammar Version: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* ignore the version numbers for now */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Grammar Version = 0x%02x", *val);
break;
case CAC_TAG_CARDURL:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL");
r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len);
if (r < 0)
return r;
break;
/*
* The following are really for file systems cards. This code only cares about CAC VM cards
*/
case CAC_TAG_PKCS15:
if (len != 1) {
sc_log(card->ctx, "TAG: PKCS15: "
"Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
/* TODO should verify that this is '0'. If it's not
* zero, we should drop out of here and let the PKCS 15
* code handle this card */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val);
break;
case CAC_TAG_DATA_MODEL:
case CAC_TAG_CARD_APDU:
case CAC_TAG_CAPABILITY_TUPLES:
case CAC_TAG_STATUS_TUPLES:
case CAC_TAG_REDIRECTION:
case CAC_TAG_ERROR_CODES:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:FSSpecific(0x%02x)", tag);
break;
case CAC_TAG_ACCESS_CONTROL:
/* TODO handle access control later */
sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len);
break;
case CAC_TAG_NEXT_CCC:
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC");
r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len);
if (r < 0)
return r;
r = cac_select_file_by_type(card, &new_path, NULL, SC_CARD_TYPE_CAC_II);
if (r < 0)
return r;
r = cac_process_CCC(card, priv);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag );
break;
}
}
return SC_SUCCESS;
}
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv)
{
u8 *tl = NULL, *val = NULL;
size_t tl_len, val_len;
int r;
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0)
goto done;
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len);
done:
if (tl)
free(tl);
if (val)
free(val);
return r;
}
/* Service Applet Table (Table 5-21) should list all the applets on the
* card, which is a good start if we don't have CCC
*/
static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv,
u8 *val, size_t val_len)
{
size_t len = 0;
u8 *val_end = val + val_len;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
for (; val < val_end; val += len) {
/* get the tag and the length */
u8 tag;
if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
break;
switch (tag) {
case CAC_TAG_APPLET_FAMILY:
if (len != 5) {
sc_log(card->ctx, "TAG: Applet Information: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Information: Family: 0x%02x", val[0]);
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
" Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
val[1], val[2], val[3], val[4]);
break;
case CAC_TAG_NUMBER_APPLETS:
if (len != 1) {
sc_log(card->ctx, "TAG: Num applets: "
"bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
break;
}
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Num applets = %hhd", *val);
break;
case CAC_TAG_APPLET_ENTRY:
/* Make sure we match the outer length */
if (len < 3 || val[2] != len - 3) {
sc_log(card->ctx, "TAG: Applet Entry: "
"bad length (%"SC_FORMAT_LEN_SIZE_T
"u) or length of internal buffer", len);
break;
}
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Applet Entry: AID", &val[3], val[2]);
/* This is SimpleTLV prefixed with applet ID (1B) */
r = cac_parse_aid(card, priv, &val[3], val[2]);
if (r < 0)
return r;
break;
default:
/* ignore tags we don't understand */
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"TAG: Unknown (0x%02x)", tag);
break;
}
}
return SC_SUCCESS;
}
/* select a CAC pki applet by index */
static int cac_select_pki_applet(sc_card_t *card, int index)
{
sc_path_t applet_path = cac_cac_pki_obj.path;
applet_path.aid.value[applet_path.aid.len-1] = index;
return cac_select_file_by_type(card, &applet_path, NULL, SC_CARD_TYPE_CAC_II);
}
/*
* Find the first existing CAC applet. If none found, then this isn't a CAC
*/
static int cac_find_first_pki_applet(sc_card_t *card, int *index_out)
{
int r, i;
for (i = 0; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
/* Try to read first two bytes of the buffer to
* make sure it is not just malfunctioning card
*/
u8 params[2] = {CAC_FILE_TAG, 2};
u8 data[2], *out_ptr = data;
size_t len = 2;
r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0,
¶ms[0], sizeof(params), &out_ptr, &len);
if (r != 2)
continue;
*index_out = i;
return SC_SUCCESS;
}
}
return SC_ERROR_OBJECT_NOT_FOUND;
}
/*
* This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets
*/
static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv)
{
int r, i;
cac_object_t pki_obj = cac_cac_pki_obj;
u8 buf[100];
u8 *val;
size_t val_len;
/* populate PKI objects */
for (i = index; i < MAX_CAC_SLOTS; i++) {
r = cac_select_pki_applet(card, i);
if (r == SC_SUCCESS) {
pki_obj.name = cac_labels[i];
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name);
pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
pki_obj.fd = i+1; /* don't use id of zero */
cac_add_object_to_list(&priv->pki_list, &pki_obj);
}
}
/* populate non-PKI objects */
for (i=0; i < cac_object_count; i++) {
r = cac_select_file_by_type(card, &cac_objects[i].path, NULL,
SC_CARD_TYPE_CAC_II);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
"CAC: obj_object found, cert_next=%d (%s),",
i, cac_objects[i].name);
cac_add_object_to_list(&priv->general_list, &cac_objects[i]);
}
}
/*
* create a cuid to simulate the cac 2 cuid.
*/
priv->cuid = cac_cac_cuid;
/* create a serial number by hashing the first 100 bytes of the
* first certificate on the card */
r = cac_select_pki_applet(card, index);
if (r < 0) {
return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
}
val = buf;
val_len = cac_read_binary(card, 0, val, sizeof(buf), 0);
if (val_len > 0) {
priv->cac_id = malloc(20);
if (priv->cac_id == NULL) {
return SC_ERROR_OUT_OF_MEMORY;
}
#ifdef ENABLE_OPENSSL
SHA1(val, val_len, priv->cac_id);
priv->cac_id_len = 20;
sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
"cuid", priv->cac_id, priv->cac_id_len);
#else
sc_log(card->ctx, "OpenSSL Required");
return SC_ERROR_NOT_SUPPORTED;
#endif /* ENABLE_OPENSSL */
}
return SC_SUCCESS;
}
static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv)
{
int r;
u8 *val = NULL;
size_t val_len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Assuming ACA is already selected */
r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len);
if (r < 0)
goto done;
r = cac_parse_ACA_service(card, priv, val, val_len);
if (r == SC_SUCCESS) {
priv->aca_path = malloc(sizeof(sc_path_t));
if (!priv->aca_path) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t));
}
done:
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* Look for a CAC card. If it exists, initialize our data structures
*/
static int cac_find_and_initialize(sc_card_t *card, int initialize)
{
int r, index;
cac_private_data_t *priv = NULL;
/* already initialized? */
if (card->drv_data) {
return SC_SUCCESS;
}
/* is this a CAC-2 specified in NIST Interagency Report 6887 -
* "Government Smart Card Interoperability Specification v2.1 July 2003" */
r = cac_select_CCC(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2");
if (!initialize) /* match card only */
return r;
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
r = cac_process_CCC(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* Even some ALT tokens can be missing CCC so we should try with ACA */
r = cac_select_ACA(card);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
r = cac_process_ACA(card, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
card->drv_data = priv;
return r;
}
}
/* is this a CAC Alt token without any accompanying structures */
r = cac_find_first_pki_applet(card, &index);
if (r == SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt");
if (!initialize) /* match card only */
return r;
if (!priv) {
priv = cac_new_private_data();
if (!priv)
return SC_ERROR_OUT_OF_MEMORY;
}
card->drv_data = priv; /* needed for the read_binary() */
r = cac_populate_cac_alt(card, index, priv);
if (r == SC_SUCCESS) {
card->type = SC_CARD_TYPE_CAC_II;
return r;
}
card->drv_data = NULL; /* reset on failure */
}
if (priv) {
cac_free_private_data(priv);
}
return r;
}
/* NOTE: returns a bool, 1 card matches, 0 it does not */
static int cac_match_card(sc_card_t *card)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
r = cac_find_and_initialize(card, 0);
return (r == SC_SUCCESS); /* never match */
}
static int cac_init(sc_card_t *card)
{
int r;
unsigned long flags;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = cac_find_and_initialize(card, 1);
if (r < 0) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_CARD);
}
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 */
card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS);
}
static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
/* CAC, like PIV needs 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();
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;
}
}
}
return iso_drv->ops->pin_cmd(card, data, tries_left);
}
static struct sc_card_operations cac_ops;
static struct sc_card_driver cac_drv = {
"Common Access Card (CAC)",
"cac",
&cac_ops,
NULL, 0, NULL
};
static struct sc_card_driver * sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
cac_ops = *iso_drv->ops;
cac_ops.match_card = cac_match_card;
cac_ops.init = cac_init;
cac_ops.finish = cac_finish;
cac_ops.select_file = cac_select_file; /* need to record object type */
cac_ops.get_challenge = cac_get_challenge;
cac_ops.read_binary = cac_read_binary;
cac_ops.write_binary = cac_write_binary;
cac_ops.set_security_env = cac_set_security_env;
cac_ops.restore_security_env = cac_restore_security_env;
cac_ops.compute_signature = cac_compute_signature;
cac_ops.decipher = cac_decipher;
cac_ops.card_ctl = cac_card_ctl;
cac_ops.pin_cmd = cac_pin_cmd;
return &cac_drv;
}
struct sc_card_driver * sc_get_cac_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_3 |
crossvul-cpp_data_bad_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-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/bad_5330_0 |
crossvul-cpp_data_bad_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));
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);
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/bad_351_9 |
crossvul-cpp_data_bad_2644_9 | /*
* Copyright (C) 2001 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: Multi-Protocol Label Switching (MPLS) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "mpls.h"
static const char *mpls_labelname[] = {
/*0*/ "IPv4 explicit NULL", "router alert", "IPv6 explicit NULL",
"implicit NULL", "rsvd",
/*5*/ "rsvd", "rsvd", "rsvd", "rsvd", "rsvd",
/*10*/ "rsvd", "rsvd", "rsvd", "rsvd", "rsvd",
/*15*/ "rsvd",
};
enum mpls_packet_type {
PT_UNKNOWN,
PT_IPV4,
PT_IPV6,
PT_OSI
};
/*
* RFC3032: MPLS label stack encoding
*/
void
mpls_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
const u_char *p;
uint32_t label_entry;
uint16_t label_stack_depth = 0;
enum mpls_packet_type pt = PT_UNKNOWN;
p = bp;
ND_PRINT((ndo, "MPLS"));
do {
ND_TCHECK2(*p, sizeof(label_entry));
if (length < sizeof(label_entry)) {
ND_PRINT((ndo, "[|MPLS], length %u", length));
return;
}
label_entry = EXTRACT_32BITS(p);
ND_PRINT((ndo, "%s(label %u",
(label_stack_depth && ndo->ndo_vflag) ? "\n\t" : " ",
MPLS_LABEL(label_entry)));
label_stack_depth++;
if (ndo->ndo_vflag &&
MPLS_LABEL(label_entry) < sizeof(mpls_labelname) / sizeof(mpls_labelname[0]))
ND_PRINT((ndo, " (%s)", mpls_labelname[MPLS_LABEL(label_entry)]));
ND_PRINT((ndo, ", exp %u", MPLS_EXP(label_entry)));
if (MPLS_STACK(label_entry))
ND_PRINT((ndo, ", [S]"));
ND_PRINT((ndo, ", ttl %u)", MPLS_TTL(label_entry)));
p += sizeof(label_entry);
length -= sizeof(label_entry);
} while (!MPLS_STACK(label_entry));
/*
* Try to figure out the packet type.
*/
switch (MPLS_LABEL(label_entry)) {
case 0: /* IPv4 explicit NULL label */
case 3: /* IPv4 implicit NULL label */
pt = PT_IPV4;
break;
case 2: /* IPv6 explicit NULL label */
pt = PT_IPV6;
break;
default:
/*
* Generally there's no indication of protocol in MPLS label
* encoding.
*
* However, draft-hsmit-isis-aal5mux-00.txt describes a
* technique for encapsulating IS-IS and IP traffic on the
* same ATM virtual circuit; you look at the first payload
* byte to determine the network layer protocol, based on
* the fact that
*
* 1) the first byte of an IP header is 0x45-0x4f
* for IPv4 and 0x60-0x6f for IPv6;
*
* 2) the first byte of an OSI CLNP packet is 0x81,
* the first byte of an OSI ES-IS packet is 0x82,
* and the first byte of an OSI IS-IS packet is
* 0x83;
*
* so the network layer protocol can be inferred from the
* first byte of the packet, if the protocol is one of the
* ones listed above.
*
* Cisco sends control-plane traffic MPLS-encapsulated in
* this fashion.
*/
ND_TCHECK(*p);
if (length < 1) {
/* nothing to print */
return;
}
switch(*p) {
case 0x45:
case 0x46:
case 0x47:
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
pt = PT_IPV4;
break;
case 0x60:
case 0x61:
case 0x62:
case 0x63:
case 0x64:
case 0x65:
case 0x66:
case 0x67:
case 0x68:
case 0x69:
case 0x6a:
case 0x6b:
case 0x6c:
case 0x6d:
case 0x6e:
case 0x6f:
pt = PT_IPV6;
break;
case 0x81:
case 0x82:
case 0x83:
pt = PT_OSI;
break;
default:
/* ok bail out - we did not figure out what it is*/
break;
}
}
/*
* Print the payload.
*/
if (pt == PT_UNKNOWN) {
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, length);
return;
}
ND_PRINT((ndo, ndo->ndo_vflag ? "\n\t" : " "));
switch (pt) {
case PT_IPV4:
ip_print(ndo, p, length);
break;
case PT_IPV6:
ip6_print(ndo, p, length);
break;
case PT_OSI:
isoclns_print(ndo, p, length, length);
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|MPLS]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_9 |
crossvul-cpp_data_good_468_0 | /*
* MPEG-4 decoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
*
* 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
*/
#define UNCHECKED_BITSTREAM_READER 1
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "error_resilience.h"
#include "hwaccel.h"
#include "idctdsp.h"
#include "internal.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "mpegvideodata.h"
#include "mpeg4video.h"
#include "h263.h"
#include "profiles.h"
#include "thread.h"
#include "xvididct.h"
/* The defines below define the number of bits that are read at once for
* reading vlc values. Changing these may improve speed and data cache needs
* be aware though that decreasing them may need the number of stages that is
* passed to get_vlc* to be increased. */
#define SPRITE_TRAJ_VLC_BITS 6
#define DC_VLC_BITS 9
#define MB_TYPE_B_VLC_BITS 4
#define STUDIO_INTRA_BITS 9
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb);
static VLC dc_lum, dc_chrom;
static VLC sprite_trajectory;
static VLC mb_type_b_vlc;
static const int mb_type_b_map[4] = {
MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
MB_TYPE_L0L1 | MB_TYPE_16x16,
MB_TYPE_L1 | MB_TYPE_16x16,
MB_TYPE_L0 | MB_TYPE_16x16,
};
/**
* Predict the ac.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir the ac prediction direction
*/
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
{
int i;
int16_t *ac_val, *ac_val1;
int8_t *const qscale_table = s->current_picture.qscale_table;
/* find prediction */
ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
ac_val1 = ac_val;
if (s->ac_pred) {
if (dir == 0) {
const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
/* left prediction */
ac_val -= 16;
if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
n == 1 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
}
} else {
const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
/* top prediction */
ac_val -= 16 * s->block_wrap[n];
if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
n == 2 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
}
}
}
/* left copy */
for (i = 1; i < 8; i++)
ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
/* top copy */
for (i = 1; i < 8; i++)
ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
}
/**
* check if the next stuff is a resync marker or the end.
* @return 0 if not
*/
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int bits_count = get_bits_count(&s->gb);
int v = show_bits(&s->gb, 16);
if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
return 0;
while (v <= 0xFF) {
if (s->pict_type == AV_PICTURE_TYPE_B ||
(v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
break;
skip_bits(&s->gb, 8 + s->pict_type);
bits_count += 8 + s->pict_type;
v = show_bits(&s->gb, 16);
}
if (bits_count + 8 >= s->gb.size_in_bits) {
v >>= 8;
v |= 0x7F >> (7 - (bits_count & 7));
if (v == 0x7F)
return s->mb_num;
} else {
if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
int len, mb_num;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
GetBitContext gb = s->gb;
skip_bits(&s->gb, 1);
align_get_bits(&s->gb);
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
mb_num = get_bits(&s->gb, mb_num_bits);
if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
mb_num= -1;
s->gb = gb;
if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
return mb_num;
}
}
return 0;
}
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int a = 2 << s->sprite_warping_accuracy;
int rho = 3 - s->sprite_warping_accuracy;
int r = 16 / a;
int alpha = 1;
int beta = 0;
int w = s->width;
int h = s->height;
int min_ab, i, w2, h2, w3, h3;
int sprite_ref[4][2];
int virtual_ref[2][2];
int64_t sprite_offset[2][2];
int64_t sprite_delta[2][2];
// only true for rectangle shapes
const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 },
{ 0, s->height }, { s->width, s->height } };
int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
if (w <= 0 || h <= 0)
return AVERROR_INVALIDDATA;
/* the decoder was not properly initialized and we cannot continue */
if (sprite_trajectory.table == NULL)
return AVERROR_INVALIDDATA;
for (i = 0; i < ctx->num_sprite_warping_points; i++) {
int length;
int x = 0, y = 0;
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
x = get_xbits(gb, length);
if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
check_marker(s->avctx, gb, "before sprite_trajectory");
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
y = get_xbits(gb, length);
check_marker(s->avctx, gb, "after sprite_trajectory");
ctx->sprite_traj[i][0] = d[i][0] = x;
ctx->sprite_traj[i][1] = d[i][1] = y;
}
for (; i < 4; i++)
ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
while ((1 << alpha) < w)
alpha++;
while ((1 << beta) < h)
beta++; /* typo in the MPEG-4 std for the definition of w' and h' */
w2 = 1 << alpha;
h2 = 1 << beta;
// Note, the 4th point isn't used for GMC
if (ctx->divx_version == 500 && ctx->divx_build == 413) {
sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
} else {
sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
}
/* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
* sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
/* This is mostly identical to the MPEG-4 std (and is totally unreadable
* because of that...). Perhaps it should be reordered to be more readable.
* The idea behind this virtual_ref mess is to be able to use shifts later
* per pixel instead of divides so the distance between points is converted
* from w&h based to w2&h2 based which are of the 2^x form. */
virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
virtual_ref[0][1] = 16 * vop_ref[0][1] +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
virtual_ref[1][0] = 16 * vop_ref[0][0] +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
switch (ctx->num_sprite_warping_points) {
case 0:
sprite_offset[0][0] =
sprite_offset[0][1] =
sprite_offset[1][0] =
sprite_offset[1][1] = 0;
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 1: // GMC only
sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
a * (vop_ref[0][0] / 2);
sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
a * (vop_ref[0][1] / 2);
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 2:
sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
ctx->sprite_shift[0] = alpha + rho;
ctx->sprite_shift[1] = alpha + rho + 2;
break;
case 3:
min_ab = FFMIN(alpha, beta);
w3 = w2 >> min_ab;
h3 = h2 >> min_ab;
sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
ctx->sprite_shift[0] = alpha + beta + rho - min_ab;
ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2;
break;
}
/* try to simplify the situation */
if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
sprite_delta[0][1] == 0 &&
sprite_delta[1][0] == 0 &&
sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
sprite_offset[0][0] >>= ctx->sprite_shift[0];
sprite_offset[0][1] >>= ctx->sprite_shift[0];
sprite_offset[1][0] >>= ctx->sprite_shift[1];
sprite_offset[1][1] >>= ctx->sprite_shift[1];
sprite_delta[0][0] = a;
sprite_delta[0][1] = 0;
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] = 0;
ctx->sprite_shift[1] = 0;
s->real_sprite_warping_points = 1;
} else {
int shift_y = 16 - ctx->sprite_shift[0];
int shift_c = 16 - ctx->sprite_shift[1];
for (i = 0; i < 2; i++) {
if (shift_c < 0 || shift_y < 0 ||
FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c ||
FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y
) {
avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
goto overflow;
}
}
for (i = 0; i < 2; i++) {
sprite_offset[0][i] *= 1 << shift_y;
sprite_offset[1][i] *= 1 << shift_c;
sprite_delta[0][i] *= 1 << shift_y;
sprite_delta[1][i] *= 1 << shift_y;
ctx->sprite_shift[i] = 16;
}
for (i = 0; i < 2; i++) {
int64_t sd[2] = {
sprite_delta[i][0] - a * (1LL<<16),
sprite_delta[i][1] - a * (1LL<<16)
};
if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX ||
llabs(sd[0]) >= INT_MAX ||
llabs(sd[1]) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
) {
avpriv_request_sample(s->avctx, "Overflow on sprite points");
goto overflow;
}
}
s->real_sprite_warping_points = ctx->num_sprite_warping_points;
}
for (i = 0; i < 4; i++) {
s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
}
return 0;
overflow:
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
return AVERROR_PATCHWELCOME;
}
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
MpegEncContext *s = &ctx->m;
int len = FFMIN(ctx->time_increment_bits + 3, 15);
get_bits(gb, len);
if (get_bits1(gb))
get_bits(gb, len);
check_marker(s->avctx, gb, "after new_pred");
return 0;
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
int header_extension = 0, mb_num, len;
/* is there enough space left for a video packet + header */
if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
return AVERROR_INVALIDDATA;
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
return AVERROR_INVALIDDATA;
}
if (ctx->shape != RECT_SHAPE) {
header_extension = get_bits1(&s->gb);
// FIXME more stuff here
}
mb_num = get_bits(&s->gb, mb_num_bits);
if (mb_num >= s->mb_num || !mb_num) {
av_log(s->avctx, AV_LOG_ERROR,
"illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
return AVERROR_INVALIDDATA;
}
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE) {
int qscale = get_bits(&s->gb, s->quant_precision);
if (qscale)
s->chroma_qscale = s->qscale = qscale;
}
if (ctx->shape == RECT_SHAPE)
header_extension = get_bits1(&s->gb);
if (header_extension) {
int time_incr = 0;
while (get_bits1(&s->gb) != 0)
time_incr++;
check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */
check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
skip_bits(&s->gb, 2); /* vop coding type */
// FIXME not rect stuff here
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits(&s->gb, 3); /* intra dc vlc threshold */
// FIXME don't just ignore everything
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
return AVERROR_INVALIDDATA;
av_log(s->avctx, AV_LOG_ERROR, "untested\n");
}
// FIXME reduced res stuff here
if (s->pict_type != AV_PICTURE_TYPE_I) {
int f_code = get_bits(&s->gb, 3); /* fcode_for */
if (f_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (f_code=0)\n");
}
if (s->pict_type == AV_PICTURE_TYPE_B) {
int b_code = get_bits(&s->gb, 3);
if (b_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (b_code=0)\n");
}
}
}
if (ctx->new_pred)
decode_new_pred(ctx, &s->gb);
return 0;
}
static void reset_studio_dc_predictors(MpegEncContext *s)
{
/* Reset DC Predictors */
s->last_dc[0] =
s->last_dc[1] =
s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
GetBitContext *gb = &s->gb;
unsigned vlc_len;
uint16_t mb_num;
if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) {
vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
mb_num = get_bits(gb, vlc_len);
if (mb_num >= s->mb_num)
return AVERROR_INVALIDDATA;
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE)
s->qscale = mpeg_get_qscale(s);
if (get_bits1(gb)) { /* slice_extension_flag */
skip_bits1(gb); /* intra_slice */
skip_bits1(gb); /* slice_VOP_id_enable */
skip_bits(gb, 6); /* slice_VOP_id */
while (get_bits1(gb)) /* extra_bit_slice */
skip_bits(gb, 8); /* extra_information_slice */
}
reset_studio_dc_predictors(s);
}
else {
return AVERROR_INVALIDDATA;
}
return 0;
}
/**
* Get the average motion vector for a GMC MB.
* @param n either 0 for the x component or 1 for y
* @return the average MV for a GMC MB
*/
static inline int get_amv(Mpeg4DecContext *ctx, int n)
{
MpegEncContext *s = &ctx->m;
int x, y, mb_v, sum, dx, dy, shift;
int len = 1 << (s->f_code + 4);
const int a = s->sprite_warping_accuracy;
if (s->workaround_bugs & FF_BUG_AMV)
len >>= s->quarter_sample;
if (s->real_sprite_warping_points == 1) {
if (ctx->divx_version == 500 && ctx->divx_build == 413)
sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
else
sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a);
} else {
dx = s->sprite_delta[n][0];
dy = s->sprite_delta[n][1];
shift = ctx->sprite_shift[0];
if (n)
dy -= 1 << (shift + a + 1);
else
dx -= 1 << (shift + a + 1);
mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
sum = 0;
for (y = 0; y < 16; y++) {
int v;
v = mb_v + dy * y;
// FIXME optimize
for (x = 0; x < 16; x++) {
sum += v >> shift;
v += dx;
}
}
sum = RSHIFT(sum, a + 8 - s->quarter_sample);
}
if (sum < -len)
sum = -len;
else if (sum >= len)
sum = len - 1;
return sum;
}
/**
* Decode the dc value.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir_ptr the prediction direction will be stored here
* @return the quantized dc
*/
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
{
int level, code;
if (n < 4)
code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
else
code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
if (code < 0 || code > 9 /* && s->nbit < 9 */) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
return AVERROR_INVALIDDATA;
}
if (code == 0) {
level = 0;
} else {
if (IS_3IV1) {
if (code == 1)
level = 2 * get_bits1(&s->gb) - 1;
else {
if (get_bits1(&s->gb))
level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
else
level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
}
} else {
level = get_xbits(&s->gb, code);
}
if (code > 8) {
if (get_bits1(&s->gb) == 0) { /* marker */
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
return AVERROR_INVALIDDATA;
}
}
}
}
return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
}
/**
* Decode first partition.
* @return number of MBs decoded or <0 if an error occurred
*/
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
/* decode first partition */
s->first_slice_line = 1;
for (; s->mb_y < s->mb_height; s->mb_y++) {
ff_init_block_index(s);
for (; s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
int cbpc;
int dir = 0;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int i;
do {
if (show_bits_long(&s->gb, 19) == DC_MARKER)
return mb_num - 1;
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
s->cbp_table[xy] = cbpc & 3;
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mb_intra = 1;
if (cbpc & 4)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->mbintra_table[xy] = 1;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->pred_dir_table[xy] = dir;
} else { /* P/S_TYPE */
int mx, my, pred_x, pred_y, bits;
int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
const int stride = s->b8_stride * 2;
try_again:
bits = show_bits(&s->gb, 17);
if (bits == MOTION_MARKER)
return mb_num - 1;
skip_bits1(&s->gb);
if (bits & 0x10000) {
/* skip mb */
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
mx = my = 0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
continue;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (cbpc == 20)
goto try_again;
s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra) {
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mbintra_table[xy] = 1;
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = 0;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = 0;
} else {
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE &&
(cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
if ((cbpc & 16) == 0) {
/* 16x16 motion prediction */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
if (!s->mcsel) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_L0;
} else {
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
} else {
int i;
s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
MB_TYPE_L0;
for (i = 0; i < 4; i++) {
int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
mot_val[0] = mx;
mot_val[1] = my;
}
}
}
}
}
s->mb_x = 0;
}
return mb_num;
}
/**
* decode second partition.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
{
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
s->mb_x = s->resync_mb_x;
s->first_slice_line = 1;
for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
ff_init_block_index(s);
for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
} else { /* P || S_TYPE */
if (IS_INTRA(s->current_picture.mb_type[xy])) {
int i;
int dir = 0;
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
s->pred_dir_table[xy] = dir;
} else if (IS_SKIP(s->current_picture.mb_type[xy])) {
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] = 0;
} else {
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
}
}
}
if (mb_num >= mb_count)
return 0;
s->mb_x = 0;
}
return 0;
}
/**
* Decode the first and second partition.
* @return <0 if error (and sets error type in the error_status_table)
*/
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num;
int ret;
const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END;
mb_num = mpeg4_decode_partition_a(ctx);
if (mb_num <= 0) {
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return mb_num ? mb_num : AVERROR_INVALIDDATA;
}
if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return AVERROR_INVALIDDATA;
}
s->mb_num_left = mb_num;
if (s->pict_type == AV_PICTURE_TYPE_I) {
while (show_bits(&s->gb, 9) == 1)
skip_bits(&s->gb, 9);
if (get_bits_long(&s->gb, 19) != DC_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first I partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} else {
while (show_bits(&s->gb, 10) == 1)
skip_bits(&s->gb, 10);
if (get_bits(&s->gb, 17) != MOTION_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first P partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
}
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, part_a_end);
ret = mpeg4_decode_partition_b(s, mb_num);
if (ret < 0) {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, ER_DC_ERROR);
return ret;
} else {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, ER_DC_END);
}
return 0;
}
/**
* Decode a block.
* @return <0 if an error occurred
*/
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
int n, int coded, int intra, int rvlc)
{
MpegEncContext *s = &ctx->m;
int level, i, last, run, qmul, qadd;
int av_uninit(dc_pred_dir);
RLTable *rl;
RL_VLC_ELEM *rl_vlc;
const uint8_t *scan_table;
// Note intra & rvlc should be optimized away if this is inlined
if (intra) {
if (ctx->use_intra_dc_vlc) {
/* DC coef */
if (s->partitioned_frame) {
level = s->dc_val[0][s->block_index[n]];
if (n < 4)
level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
else
level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
} else {
level = mpeg4_decode_dc(s, n, &dc_pred_dir);
if (level < 0)
return level;
}
block[0] = level;
i = 0;
} else {
i = -1;
ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
}
if (!coded)
goto not_coded;
if (rvlc) {
rl = &ff_rvlc_rl_intra;
rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
} else {
rl = &ff_mpeg4_rl_intra;
rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
}
if (s->ac_pred) {
if (dc_pred_dir == 0)
scan_table = s->intra_v_scantable.permutated; /* left */
else
scan_table = s->intra_h_scantable.permutated; /* top */
} else {
scan_table = s->intra_scantable.permutated;
}
qmul = 1;
qadd = 0;
} else {
i = -1;
if (!coded) {
s->block_last_index[n] = i;
return 0;
}
if (rvlc)
rl = &ff_rvlc_rl_inter;
else
rl = &ff_h263_rl_inter;
scan_table = s->intra_scantable.permutated;
if (s->mpeg_quant) {
qmul = 1;
qadd = 0;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[0];
} else {
qmul = s->qscale << 1;
qadd = (s->qscale - 1) | 1;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
}
}
{
OPEN_READER(re, &s->gb);
for (;;) {
UPDATE_CACHE(re, &s->gb);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
if (level == 0) {
/* escape */
if (rvlc) {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_UBITS(re, &s->gb, 11);
SKIP_CACHE(re, &s->gb, 11);
if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 5);
level = level * qmul + qadd;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
i += run + 1;
if (last)
i += 192;
} else {
int cache;
cache = GET_CACHE(re, &s->gb);
if (IS_3IV1)
cache ^= 0xC0000000;
if (cache & 0x80000000) {
if (cache & 0x40000000) {
/* third escape */
SKIP_CACHE(re, &s->gb, 2);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (IS_3IV1) {
level = SHOW_SBITS(re, &s->gb, 12);
LAST_SKIP_BITS(re, &s->gb, 12);
} else {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_SBITS(re, &s->gb, 12);
SKIP_CACHE(re, &s->gb, 12);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
}
#if 0
if (s->error_recognition >= FF_ER_COMPLIANT) {
const int abs_level= FFABS(level);
if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
const int run1= run - rl->max_run[last][abs_level] - 1;
if (abs_level <= rl->max_level[last][run]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (s->error_recognition > FF_ER_COMPLIANT) {
if (abs_level <= rl->max_level[last][run]*2) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
return AVERROR_INVALIDDATA;
}
}
}
}
#endif
if (level > 0)
level = level * qmul + qadd;
else
level = level * qmul - qadd;
if ((unsigned)(level + 2048) > 4095) {
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
if (level > 2560 || level < -2560) {
av_log(s->avctx, AV_LOG_ERROR,
"|level| overflow in 3. esc, qp=%d\n",
s->qscale);
return AVERROR_INVALIDDATA;
}
}
level = level < 0 ? -2048 : 2047;
}
i += run + 1;
if (last)
i += 192;
} else {
/* second escape */
SKIP_BITS(re, &s->gb, 2);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
} else {
/* first escape */
SKIP_BITS(re, &s->gb, 1);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run;
level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
}
} else {
i += run;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
if (i > 62) {
i -= 192;
if (i & (~63)) {
av_log(s->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
block[scan_table[i]] = level;
break;
}
block[scan_table[i]] = level;
}
CLOSE_READER(re, &s->gb);
}
not_coded:
if (intra) {
if (!ctx->use_intra_dc_vlc) {
block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
i -= i >> 31; // if (i == -1) i = 0;
}
ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
if (s->ac_pred)
i = 63; // FIXME not optimal
}
s->block_last_index[n] = i;
return 0;
}
/**
* decode partition C of one MB.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbp, mb_type;
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
mb_type = s->current_picture.mb_type[xy];
cbp = s->cbp_table[xy];
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (s->current_picture.qscale_table[xy] != s->qscale)
ff_set_qscale(s, s->current_picture.qscale_table[xy]);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
int i;
for (i = 0; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
}
s->mb_intra = IS_INTRA(mb_type);
if (IS_SKIP(mb_type)) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S
&& ctx->vol_sprite_usage == GMC_SPRITE) {
s->mcsel = 1;
s->mb_skipped = 0;
} else {
s->mcsel = 0;
s->mb_skipped = 1;
}
} else if (s->mb_intra) {
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
} else if (!s->mb_intra) {
// s->mcsel = 0; // FIXME do we need to init that?
s->mv_dir = MV_DIR_FORWARD;
if (IS_8X8(mb_type)) {
s->mv_type = MV_TYPE_8X8;
} else {
s->mv_type = MV_TYPE_16X16;
}
}
} else { /* I-Frame */
s->mb_intra = 1;
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
}
if (!IS_SKIP(mb_type)) {
int i;
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"texture corrupted at %d %d %d\n",
s->mb_x, s->mb_y, s->mb_intra);
return AVERROR_INVALIDDATA;
}
cbp += cbp;
}
}
/* per-MB end of slice check */
if (--s->mb_num_left <= 0) {
if (mpeg4_is_resync(ctx))
return SLICE_END;
else
return SLICE_NOEND;
} else {
if (mpeg4_is_resync(ctx)) {
const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
if (s->cbp_table[xy + delta])
return SLICE_END;
}
return SLICE_OK;
}
}
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
int16_t *mot_val;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
av_assert2(s->h263_pred);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
do {
if (get_bits1(&s->gb)) {
/* skip mb */
s->mb_intra = 0;
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 1;
s->mv[0][0][0] = get_amv(ctx, 0);
s->mv[0][0][1] = get_amv(ctx, 1);
s->mb_skipped = 0;
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 0;
s->mv[0][0][0] = 0;
s->mv[0][0][1] = 0;
s->mb_skipped = 1;
}
goto end;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 20);
s->bdsp.clear_blocks(s->block[0]);
dquant = cbpc & 8;
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra)
goto intra;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if ((!s->progressive_sequence) &&
(cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
s->interlaced_dct = get_bits1(&s->gb);
s->mv_dir = MV_DIR_FORWARD;
if ((cbpc & 16) == 0) {
if (s->mcsel) {
s->current_picture.mb_type[xy] = MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
/* 16x16 global motion prediction */
s->mv_type = MV_TYPE_16X16;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
} else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
MB_TYPE_L0 |
MB_TYPE_INTERLACED;
/* 16x8 field motion prediction */
s->mv_type = MV_TYPE_FIELD;
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
/* 16x16 motion prediction */
s->mv_type = MV_TYPE_16X16;
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
s->mv_type = MV_TYPE_8X8;
for (i = 0; i < 4; i++) {
mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
mot_val[0] = mx;
mot_val[1] = my;
}
}
} else if (s->pict_type == AV_PICTURE_TYPE_B) {
int modb1; // first bit of modb
int modb2; // second bit of modb
int mb_type;
s->mb_intra = 0; // B-frames never contain intra blocks
s->mcsel = 0; // ... true gmc blocks
if (s->mb_x == 0) {
for (i = 0; i < 2; i++) {
s->last_mv[i][0][0] =
s->last_mv[i][0][1] =
s->last_mv[i][1][0] =
s->last_mv[i][1][1] = 0;
}
ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
}
/* if we skipped it in the future P-frame than skip it now too */
s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
if (s->mb_skipped) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] =
s->mv[0][0][1] =
s->mv[1][0][0] =
s->mv[1][0][1] = 0;
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
goto end;
}
modb1 = get_bits1(&s->gb);
if (modb1) {
// like MB_TYPE_B_DIRECT but no vectors coded
mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
cbp = 0;
} else {
modb2 = get_bits1(&s->gb);
mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
if (mb_type < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
return AVERROR_INVALIDDATA;
}
mb_type = mb_type_b_map[mb_type];
if (modb2) {
cbp = 0;
} else {
s->bdsp.clear_blocks(s->block[0]);
cbp = get_bits(&s->gb, 6);
}
if ((!IS_DIRECT(mb_type)) && cbp) {
if (get_bits1(&s->gb))
ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
}
if (!s->progressive_sequence) {
if (cbp)
s->interlaced_dct = get_bits1(&s->gb);
if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
mb_type &= ~MB_TYPE_16x16;
if (USES_LIST(mb_type, 0)) {
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
}
if (USES_LIST(mb_type, 1)) {
s->field_select[1][0] = get_bits1(&s->gb);
s->field_select[1][1] = get_bits1(&s->gb);
}
}
}
s->mv_dir = 0;
if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
s->mv_type = MV_TYPE_16X16;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
s->last_mv[0][1][0] =
s->last_mv[0][0][0] =
s->mv[0][0][0] = mx;
s->last_mv[0][1][1] =
s->last_mv[0][0][1] =
s->mv[0][0][1] = my;
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
s->last_mv[1][1][0] =
s->last_mv[1][0][0] =
s->mv[1][0][0] = mx;
s->last_mv[1][1][1] =
s->last_mv[1][0][1] =
s->mv[1][0][1] = my;
}
} else if (!IS_DIRECT(mb_type)) {
s->mv_type = MV_TYPE_FIELD;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
s->last_mv[0][i][0] =
s->mv[0][i][0] = mx;
s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
}
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
s->last_mv[1][i][0] =
s->mv[1][i][0] = mx;
s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
}
}
}
}
if (IS_DIRECT(mb_type)) {
if (IS_SKIP(mb_type)) {
mx =
my = 0;
} else {
mx = ff_h263_decode_motion(s, 0, 1);
my = ff_h263_decode_motion(s, 0, 1);
}
s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
}
s->current_picture.mb_type[xy] = mb_type;
} else { /* I-Frame */
do {
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
dquant = cbpc & 4;
s->mb_intra = 1;
intra:
s->ac_pred = get_bits1(&s->gb);
if (s->ac_pred)
s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
else
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if (!s->progressive_sequence)
s->interlaced_dct = get_bits1(&s->gb);
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
goto end;
}
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
end:
/* per-MB end of slice check */
if (s->codec_id == AV_CODEC_ID_MPEG4) {
int next = mpeg4_is_resync(ctx);
if (next) {
if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
return AVERROR_INVALIDDATA;
} else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
return SLICE_END;
if (s->pict_type == AV_PICTURE_TYPE_B) {
const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
ff_thread_await_progress(&s->next_picture_ptr->tf,
(s->mb_x + delta >= s->mb_width)
? FFMIN(s->mb_y + 1, s->mb_height - 1)
: s->mb_y, 0);
if (s->next_picture.mbskip_table[xy + delta])
return SLICE_OK;
}
return SLICE_END;
}
}
return SLICE_OK;
}
/* As per spec, studio start code search isn't the same as the old type of start code */
static void next_start_code_studio(GetBitContext *gb)
{
align_get_bits(gb);
while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) {
get_bits(gb, 8);
}
}
/* additional_code, vlc index */
static const uint8_t ac_state_tab[22][2] =
{
{0, 0},
{0, 1},
{1, 1},
{2, 1},
{3, 1},
{4, 1},
{5, 1},
{1, 2},
{2, 2},
{3, 2},
{4, 2},
{5, 2},
{6, 2},
{1, 3},
{2, 4},
{3, 5},
{4, 6},
{5, 7},
{6, 8},
{7, 9},
{8, 10},
{0, 11}
};
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
/* StudioMacroblock */
/* Assumes I-VOP */
s->mb_intra = 1;
if (get_bits1(&s->gb)) { /* compression_mode */
/* DCT */
/* macroblock_type, 1 or 2-bit VLC */
if (!get_bits1(&s->gb)) {
skip_bits1(&s->gb);
s->qscale = mpeg_get_qscale(s);
}
for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
} else {
/* DPCM */
check_marker(s->avctx, &s->gb, "DPCM block start");
avpriv_request_sample(s->avctx, "DPCM encoded block");
next_start_code_studio(&s->gb);
return SLICE_ERROR;
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
return SLICE_OK;
}
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
{
int hours, minutes, seconds;
if (!show_bits(gb, 23)) {
av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
return AVERROR_INVALIDDATA;
}
hours = get_bits(gb, 5);
minutes = get_bits(gb, 6);
check_marker(s->avctx, gb, "in gop_header");
seconds = get_bits(gb, 6);
s->time_base = seconds + 60*(minutes + 60*hours);
skip_bits1(gb);
skip_bits1(gb);
return 0;
}
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
{
*profile = get_bits(gb, 4);
*level = get_bits(gb, 4);
// for Simple profile, level 0
if (*profile == 0 && *level == 8) {
*level = 0;
}
return 0;
}
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
{
int visual_object_type;
int is_visual_object_identifier = get_bits1(gb);
if (is_visual_object_identifier) {
skip_bits(gb, 4+3);
}
visual_object_type = get_bits(gb, 4);
if (visual_object_type == VOT_VIDEO_ID ||
visual_object_type == VOT_STILL_TEXTURE_ID) {
int video_signal_type = get_bits1(gb);
if (video_signal_type) {
int video_range, color_description;
skip_bits(gb, 3); // video_format
video_range = get_bits1(gb);
color_description = get_bits1(gb);
s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
if (color_description) {
s->avctx->color_primaries = get_bits(gb, 8);
s->avctx->color_trc = get_bits(gb, 8);
s->avctx->colorspace = get_bits(gb, 8);
}
}
}
return 0;
}
static void mpeg4_load_default_matrices(MpegEncContext *s)
{
int i, v;
/* load default matrices */
for (i = 0; i < 64; i++) {
int j = s->idsp.idct_permutation[i];
v = ff_mpeg4_default_intra_matrix[i];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
v = ff_mpeg4_default_non_intra_matrix[i];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
}
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height, vo_ver_id;
/* vol header */
skip_bits(gb, 1); /* random access */
s->vo_type = get_bits(gb, 8);
/* If we are in studio profile (per vo_type), check if its all consistent
* and if so continue pass control to decode_studio_vol_header().
* elIf something is inconsistent, error out
* else continue with (non studio) vol header decpoding.
*/
if (s->vo_type == CORE_STUDIO_VO_TYPE ||
s->vo_type == SIMPLE_STUDIO_VO_TYPE) {
if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO)
return AVERROR_INVALIDDATA;
s->studio_profile = 1;
s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO;
return decode_studio_vol_header(ctx, gb);
} else if (s->studio_profile) {
return AVERROR_PATCHWELCOME;
}
if (get_bits1(gb) != 0) { /* is_ol_id */
vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
skip_bits(gb, 3); /* vo_priority */
} else {
vo_ver_id = 1;
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
int chroma_format = get_bits(gb, 2);
if (chroma_format != CHROMA_420)
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
s->low_delay = get_bits1(gb);
if (get_bits1(gb)) { /* vbv parameters */
get_bits(gb, 15); /* first_half_bitrate */
check_marker(s->avctx, gb, "after first_half_bitrate");
get_bits(gb, 15); /* latter_half_bitrate */
check_marker(s->avctx, gb, "after latter_half_bitrate");
get_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
get_bits(gb, 3); /* latter_half_vbv_buffer_size */
get_bits(gb, 11); /* first_half_vbv_occupancy */
check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
get_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
}
} else {
/* is setting low delay flag only once the smartest thing to do?
* low delay detection will not be overridden. */
if (s->picture_number == 0) {
switch(s->vo_type) {
case SIMPLE_VO_TYPE:
case ADV_SIMPLE_VO_TYPE:
s->low_delay = 1;
break;
default:
s->low_delay = 0;
}
}
}
ctx->shape = get_bits(gb, 2); /* vol shape */
if (ctx->shape != RECT_SHAPE)
av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
skip_bits(gb, 4); /* video_object_layer_shape_extension */
}
check_marker(s->avctx, gb, "before time_increment_resolution");
s->avctx->framerate.num = get_bits(gb, 16);
if (!s->avctx->framerate.num) {
av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
return AVERROR_INVALIDDATA;
}
ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
if (ctx->time_increment_bits < 1)
ctx->time_increment_bits = 1;
check_marker(s->avctx, gb, "before fixed_vop_rate");
if (get_bits1(gb) != 0) /* fixed_vop_rate */
s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
else
s->avctx->framerate.den = 1;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
ctx->t_frame = 0;
if (ctx->shape != BIN_ONLY_SHAPE) {
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before width");
width = get_bits(gb, 13);
check_marker(s->avctx, gb, "before height");
height = get_bits(gb, 13);
check_marker(s->avctx, gb, "after height");
if (width && height && /* they should be non zero but who knows */
!(s->width && s->codec_tag == AV_RL32("MP4S"))) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->progressive_sequence =
s->progressive_frame = get_bits1(gb) ^ 1;
s->interlaced_dct = 0;
if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */
"MPEG-4 OBMC not supported (very likely buggy encoder)\n");
if (vo_ver_id == 1)
ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
else
ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE) {
if (ctx->vol_sprite_usage == STATIC_SPRITE) {
skip_bits(gb, 13); // sprite_width
check_marker(s->avctx, gb, "after sprite_width");
skip_bits(gb, 13); // sprite_height
check_marker(s->avctx, gb, "after sprite_height");
skip_bits(gb, 13); // sprite_left
check_marker(s->avctx, gb, "after sprite_left");
skip_bits(gb, 13); // sprite_top
check_marker(s->avctx, gb, "after sprite_top");
}
ctx->num_sprite_warping_points = get_bits(gb, 6);
if (ctx->num_sprite_warping_points > 3) {
av_log(s->avctx, AV_LOG_ERROR,
"%d sprite_warping_points\n",
ctx->num_sprite_warping_points);
ctx->num_sprite_warping_points = 0;
return AVERROR_INVALIDDATA;
}
s->sprite_warping_accuracy = get_bits(gb, 2);
ctx->sprite_brightness_change = get_bits1(gb);
if (ctx->vol_sprite_usage == STATIC_SPRITE)
skip_bits1(gb); // low_latency_sprite
}
// FIXME sadct disable bit if verid!=1 && shape not rect
if (get_bits1(gb) == 1) { /* not_8_bit */
s->quant_precision = get_bits(gb, 4); /* quant_precision */
if (get_bits(gb, 4) != 8) /* bits_per_pixel */
av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
if (s->quant_precision != 5)
av_log(s->avctx, AV_LOG_ERROR,
"quant precision %d\n", s->quant_precision);
if (s->quant_precision<3 || s->quant_precision>9) {
s->quant_precision = 5;
}
} else {
s->quant_precision = 5;
}
// FIXME a bunch of grayscale shape things
if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
int i, v;
mpeg4_load_default_matrices(s);
/* load custom intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
}
/* load custom non intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = last;
s->chroma_inter_matrix[j] = last;
}
}
// FIXME a bunch of grayscale shape things
}
if (vo_ver_id != 1)
s->quarter_sample = get_bits1(gb);
else
s->quarter_sample = 0;
if (get_bits_left(gb) < 4) {
av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
return AVERROR_INVALIDDATA;
}
if (!get_bits1(gb)) {
int pos = get_bits_count(gb);
int estimation_method = get_bits(gb, 2);
if (estimation_method < 2) {
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */
ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */
ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (estimation_method == 1) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */
}
} else
av_log(s->avctx, AV_LOG_ERROR,
"Invalid Complexity estimation method %d\n",
estimation_method);
} else {
no_cplx_est:
ctx->cplx_estimation_trash_i =
ctx->cplx_estimation_trash_p =
ctx->cplx_estimation_trash_b = 0;
}
ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
s->data_partitioning = get_bits1(gb);
if (s->data_partitioning)
ctx->rvlc = get_bits1(gb);
if (vo_ver_id != 1) {
ctx->new_pred = get_bits1(gb);
if (ctx->new_pred) {
av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
skip_bits(gb, 2); /* requested upstream message type */
skip_bits1(gb); /* newpred segment type */
}
if (get_bits1(gb)) // reduced_res_vop
av_log(s->avctx, AV_LOG_ERROR,
"reduced resolution VOP not supported\n");
} else {
ctx->new_pred = 0;
}
ctx->scalability = get_bits1(gb);
if (ctx->scalability) {
GetBitContext bak = *gb;
int h_sampling_factor_n;
int h_sampling_factor_m;
int v_sampling_factor_n;
int v_sampling_factor_m;
skip_bits1(gb); // hierarchy_type
skip_bits(gb, 4); /* ref_layer_id */
skip_bits1(gb); /* ref_layer_sampling_dir */
h_sampling_factor_n = get_bits(gb, 5);
h_sampling_factor_m = get_bits(gb, 5);
v_sampling_factor_n = get_bits(gb, 5);
v_sampling_factor_m = get_bits(gb, 5);
ctx->enhancement_type = get_bits1(gb);
if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
/* illegal scalability header (VERY broken encoder),
* trying to workaround */
ctx->scalability = 0;
*gb = bak;
} else
av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
// bin shape stuff FIXME
}
}
if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n",
s->avctx->framerate.den, s->avctx->framerate.num,
ctx->time_increment_bits,
s->quant_precision,
s->progressive_sequence,
s->low_delay,
ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
);
}
return 0;
}
/**
* Decode the user data stuff in the header.
* Also initializes divx/xvid/lavc_version/build.
*/
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
char buf[256];
int i;
int e;
int ver = 0, build = 0, ver2 = 0, ver3 = 0;
char last;
for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
if (show_bits(gb, 23) == 0)
break;
buf[i] = get_bits(gb, 8);
}
buf[i] = 0;
/* divx detection */
e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
if (e < 2)
e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
if (e >= 2) {
ctx->divx_version = ver;
ctx->divx_build = build;
s->divx_packed = e == 3 && last == 'p';
}
/* libavcodec detection */
e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
if (e != 4)
e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
if (e != 4) {
e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
if (e > 1) {
if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
av_log(s->avctx, AV_LOG_WARNING,
"Unknown Lavc version string encountered, %d.%d.%d; "
"clamping sub-version values to 8-bits.\n",
ver, ver2, ver3);
}
build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
}
}
if (e != 4) {
if (strcmp(buf, "ffmpeg") == 0)
ctx->lavc_build = 4600;
}
if (e == 4)
ctx->lavc_build = build;
/* Xvid detection */
e = sscanf(buf, "XviD%d", &build);
if (e == 1)
ctx->xvid_build = build;
return 0;
}
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
if (s->codec_tag == AV_RL32("XVID") ||
s->codec_tag == AV_RL32("XVIX") ||
s->codec_tag == AV_RL32("RMP4") ||
s->codec_tag == AV_RL32("ZMP4") ||
s->codec_tag == AV_RL32("SIPP"))
ctx->xvid_build = 0;
}
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
ctx->vol_control_parameters == 0)
ctx->divx_version = 400; // divx 4
if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
ctx->divx_version =
ctx->divx_build = -1;
}
if (s->workaround_bugs & FF_BUG_AUTODETECT) {
if (s->codec_tag == AV_RL32("XVIX"))
s->workaround_bugs |= FF_BUG_XVID_ILACE;
if (s->codec_tag == AV_RL32("UMP4"))
s->workaround_bugs |= FF_BUG_UMP4;
if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->divx_version > 502 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
if (ctx->xvid_build <= 3U)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->xvid_build <= 1U)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->xvid_build <= 12U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->xvid_build <= 32U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
#define SET_QPEL_FUNC(postfix1, postfix2) \
s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \
s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \
s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2;
if (ctx->lavc_build < 4653U)
s->workaround_bugs |= FF_BUG_STD_QPEL;
if (ctx->lavc_build < 4655U)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->lavc_build < 4670U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->lavc_build <= 4712U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
if ((ctx->lavc_build&0xFF) >= 100) {
if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
(ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
)
s->workaround_bugs |= FF_BUG_IEDGE;
}
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->divx_version < 500U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
}
if (s->workaround_bugs & FF_BUG_STD_QPEL) {
SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
}
if (avctx->debug & FF_DEBUG_BUGS)
av_log(s->avctx, AV_LOG_DEBUG,
"bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
s->codec_id == AV_CODEC_ID_MPEG4 &&
avctx->idct_algo == FF_IDCT_AUTO) {
avctx->idct_algo = FF_IDCT_XVID;
ff_mpv_idct_init(s);
return 1;
}
return 0;
}
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int time_incr, time_increment;
int64_t pts;
s->mcsel = 0;
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */
if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
s->low_delay = 0;
}
s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
if (s->partitioned_frame)
s->decode_mb = mpeg4_decode_partitioned_mb;
else
s->decode_mb = mpeg4_decode_mb;
time_incr = 0;
while (get_bits1(gb) != 0)
time_incr++;
check_marker(s->avctx, gb, "before time_increment");
if (ctx->time_increment_bits == 0 ||
!(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
for (ctx->time_increment_bits = 1;
ctx->time_increment_bits < 16;
ctx->time_increment_bits++) {
if (s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE)) {
if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
break;
} else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
break;
}
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
s->avctx->framerate.num = 1<<ctx->time_increment_bits;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
}
}
if (IS_3IV1)
time_increment = get_bits1(gb); // FIXME investigate further
else
time_increment = get_bits(gb, ctx->time_increment_bits);
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->last_time_base = s->time_base;
s->time_base += time_incr;
s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
if (s->workaround_bugs & FF_BUG_UMP4) {
if (s->time < s->last_non_b_time) {
/* header is not mpeg-4-compatible, broken encoder,
* trying to workaround */
s->time_base++;
s->time += s->avctx->framerate.num;
}
}
s->pp_time = s->time - s->last_non_b_time;
s->last_non_b_time = s->time;
} else {
s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
if (s->pp_time <= s->pb_time ||
s->pp_time <= s->pp_time - s->pb_time ||
s->pp_time <= 0) {
/* messed up order, maybe after seeking? skipping current B-frame */
return FRAME_SKIPPED;
}
ff_mpeg4_init_direct_mv(s);
if (ctx->t_frame == 0)
ctx->t_frame = s->pb_time;
if (ctx->t_frame == 0)
ctx->t_frame = 1; // 1/0 protection
s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
s->pb_field_time = 2;
s->pp_field_time = 4;
if (!s->progressive_sequence)
return FRAME_SKIPPED;
}
}
if (s->avctx->framerate.den)
pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
else
pts = AV_NOPTS_VALUE;
ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
check_marker(s->avctx, gb, "before vop_coded");
/* vop coded */
if (get_bits1(gb) != 1) {
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
return FRAME_SKIPPED;
}
if (ctx->new_pred)
decode_new_pred(ctx, gb);
if (ctx->shape != BIN_ONLY_SHAPE &&
(s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE))) {
/* rounding type for motion estimation */
s->no_rounding = get_bits1(gb);
} else {
s->no_rounding = 0;
}
// FIXME reduced res stuff
if (ctx->shape != RECT_SHAPE) {
if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
skip_bits(gb, 13); /* width */
check_marker(s->avctx, gb, "after width");
skip_bits(gb, 13); /* height */
check_marker(s->avctx, gb, "after height");
skip_bits(gb, 13); /* hor_spat_ref */
check_marker(s->avctx, gb, "after hor_spat_ref");
skip_bits(gb, 13); /* ver_spat_ref */
}
skip_bits1(gb); /* change_CR_disable */
if (get_bits1(gb) != 0)
skip_bits(gb, 8); /* constant_alpha_value */
}
// FIXME complexity estimation stuff
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits_long(gb, ctx->cplx_estimation_trash_i);
if (s->pict_type != AV_PICTURE_TYPE_I)
skip_bits_long(gb, ctx->cplx_estimation_trash_p);
if (s->pict_type == AV_PICTURE_TYPE_B)
skip_bits_long(gb, ctx->cplx_estimation_trash_b);
if (get_bits_left(gb) < 3) {
av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
return AVERROR_INVALIDDATA;
}
ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
if (!s->progressive_sequence) {
s->top_field_first = get_bits1(gb);
s->alternate_scan = get_bits1(gb);
} else
s->alternate_scan = 0;
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
if (s->pict_type == AV_PICTURE_TYPE_S) {
if((ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE)) {
if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
return AVERROR_INVALIDDATA;
if (ctx->sprite_brightness_change)
av_log(s->avctx, AV_LOG_ERROR,
"sprite_brightness_change not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
} else {
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
}
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (qscale=0)\n");
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
if (s->pict_type != AV_PICTURE_TYPE_I) {
s->f_code = get_bits(gb, 3); /* fcode_for */
if (s->f_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (f_code=0)\n");
s->f_code = 1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
} else
s->f_code = 1;
if (s->pict_type == AV_PICTURE_TYPE_B) {
s->b_code = get_bits(gb, 3);
if (s->b_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG4 header (b_code=0)\n");
s->b_code=1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
}
} else
s->b_code = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG,
"qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
s->qscale, s->f_code, s->b_code,
s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
s->top_field_first, s->quarter_sample ? "q" : "h",
s->data_partitioning, ctx->resync_marker,
ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
1 - s->no_rounding, s->vo_type,
ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
ctx->cplx_estimation_trash_b,
s->time,
time_increment
);
}
if (!ctx->scalability) {
if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
skip_bits1(gb); // vop shape coding type
} else {
if (ctx->enhancement_type) {
int load_backward_shape = get_bits1(gb);
if (load_backward_shape)
av_log(s->avctx, AV_LOG_ERROR,
"load backward shape isn't supported\n");
}
skip_bits(gb, 2); // ref_select_code
}
}
/* detect buggy encoders which don't set the low_delay flag
* (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
* easily (although it's buggy too) */
if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
ctx->divx_version == -1 && s->picture_number == 0) {
av_log(s->avctx, AV_LOG_WARNING,
"looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
s->low_delay = 1;
}
s->picture_number++; // better than pic number==0 always ;)
// FIXME add short header support
s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
if (s->workaround_bugs & FF_BUG_EDGE) {
s->h_edge_pos = s->width;
s->v_edge_pos = s->height;
}
return 0;
}
static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
return 0;
}
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
{
uint32_t startcode;
uint8_t extension_type;
startcode = show_bits_long(gb, 32);
if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
skip_bits_long(gb, 32);
extension_type = get_bits(gb, 4);
if (extension_type == QUANT_MATRIX_EXT_ID)
read_quant_matrix_ext(s, gb);
}
}
}
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
skip_bits(gb, 16); /* Time_code[63..48] */
check_marker(s->avctx, gb, "after Time_code[63..48]");
skip_bits(gb, 16); /* Time_code[47..32] */
check_marker(s->avctx, gb, "after Time_code[47..32]");
skip_bits(gb, 16); /* Time_code[31..16] */
check_marker(s->avctx, gb, "after Time_code[31..16]");
skip_bits(gb, 16); /* Time_code[15..0] */
check_marker(s->avctx, gb, "after Time_code[15..0]");
skip_bits(gb, 4); /* reserved_bits */
}
/**
* Decode the next studio vop header.
* @return <0 if something went wrong
*/
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int visual_object_type;
skip_bits(gb, 4); /* visual_object_verid */
visual_object_type = get_bits(gb, 4);
if (visual_object_type != VOT_VIDEO_ID) {
avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
return AVERROR_PATCHWELCOME;
}
next_start_code_studio(gb);
extension_and_user_data(s, gb, 1);
return 0;
}
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height;
int bits_per_raw_sample;
// random_accessible_vol and video_object_type_indication have already
// been read by the caller decode_vol_header()
skip_bits(gb, 4); /* video_object_layer_verid */
ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
skip_bits(gb, 4); /* video_object_layer_shape_extension */
skip_bits1(gb); /* progressive_sequence */
if (ctx->shape != BIN_ONLY_SHAPE) {
ctx->rgb = get_bits1(gb); /* rgb_components */
s->chroma_format = get_bits(gb, 2); /* chroma_format */
if (!s->chroma_format) {
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
return AVERROR_INVALIDDATA;
}
bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
if (bits_per_raw_sample == 10) {
if (ctx->rgb) {
s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
}
else {
s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
}
}
else {
avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
return AVERROR_PATCHWELCOME;
}
s->avctx->bits_per_raw_sample = bits_per_raw_sample;
}
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before video_object_layer_width");
width = get_bits(gb, 14); /* video_object_layer_width */
check_marker(s->avctx, gb, "before video_object_layer_height");
height = get_bits(gb, 14); /* video_object_layer_height */
check_marker(s->avctx, gb, "after video_object_layer_height");
/* Do the same check as non-studio profile */
if (width && height) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
skip_bits(gb, 4); /* frame_rate_code */
skip_bits(gb, 15); /* first_half_bit_rate */
check_marker(s->avctx, gb, "after first_half_bit_rate");
skip_bits(gb, 15); /* latter_half_bit_rate */
check_marker(s->avctx, gb, "after latter_half_bit_rate");
skip_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
skip_bits(gb, 11); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
s->low_delay = get_bits1(gb);
s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
next_start_code_studio(gb);
extension_and_user_data(s, gb, 2);
return 0;
}
/**
* Decode MPEG-4 headers.
* @return <0 if no VOP found (or a damaged one)
* FRAME_SKIPPED if a not coded VOP is found
* 0 if a VOP is found
*/
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
// If we have not switched to studio profile than we also did not switch bps
// that means something else (like a previous instance) outside set bps which
// would be inconsistant with the currect state, thus reset it
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
av_cold void ff_mpeg4videodec_static_init(void) {
static int done = 0;
if (!done) {
ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_lum[0][1], 2, 1,
&ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_chrom[0][1], 2, 1,
&ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
&ff_sprite_trajectory_tab[0][1], 4, 2,
&ff_sprite_trajectory_tab[0][0], 4, 2, 128);
INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
&ff_mb_type_b_tab[0][1], 2, 1,
&ff_mb_type_b_tab[0][0], 2, 1, 16);
done = 1;
}
}
int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
/* divx 5.01+ bitstream reorder stuff */
/* Since this clobbers the input buffer and hwaccel codecs still need the
* data during hwaccel->end_frame we should not do this any earlier */
if (s->divx_packed) {
int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
int startcode_found = 0;
if (buf_size - current_pos > 7) {
int i;
for (i = current_pos; i < buf_size - 4; i++)
if (buf[i] == 0 &&
buf[i + 1] == 0 &&
buf[i + 2] == 1 &&
buf[i + 3] == 0xB6) {
startcode_found = !(buf[i + 4] & 0x40);
break;
}
}
if (startcode_found) {
if (!ctx->showed_packed_warning) {
av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
"wasteful way to store B-frames ('packed B-frames'). "
"Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
ctx->showed_packed_warning = 1;
}
av_fast_padded_malloc(&s->bitstream_buffer,
&s->allocated_bitstream_buffer_size,
buf_size - current_pos);
if (!s->bitstream_buffer) {
s->bitstream_buffer_size = 0;
return AVERROR(ENOMEM);
}
memcpy(s->bitstream_buffer, buf + current_pos,
buf_size - current_pos);
s->bitstream_buffer_size = buf_size - current_pos;
}
}
return 0;
}
#if HAVE_THREADS
static int mpeg4_update_thread_context(AVCodecContext *dst,
const AVCodecContext *src)
{
Mpeg4DecContext *s = dst->priv_data;
const Mpeg4DecContext *s1 = src->priv_data;
int init = s->m.context_initialized;
int ret = ff_mpeg_update_thread_context(dst, src);
if (ret < 0)
return ret;
memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
ff_xvid_idct_init(&s->m.idsp, dst);
return 0;
}
#endif
static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx)
{
int i, ret;
for (i = 0; i < 12; i++) {
ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22,
&ff_mpeg4_studio_intra[i][0][1], 4, 2,
&ff_mpeg4_studio_intra[i][0][0], 4, 2,
0);
if (ret < 0)
return ret;
}
ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_luma[0][1], 4, 2,
&ff_mpeg4_studio_dc_luma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_chroma[0][1], 4, 2,
&ff_mpeg4_studio_dc_chroma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
int ret;
ctx->divx_version =
ctx->divx_build =
ctx->xvid_build =
ctx->lavc_build = -1;
if ((ret = ff_h263_decode_init(avctx)) < 0)
return ret;
ff_mpeg4videodec_static_init();
if ((ret = init_studio_vlcs(ctx)) < 0)
return ret;
s->h263_pred = 1;
s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
s->decode_mb = mpeg4_decode_mb;
ctx->time_increment_bits = 4; /* default value for broken headers */
avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
avctx->internal->allocate_progress = 1;
return 0;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
int i;
if (!avctx->internal->is_copy) {
for (i = 0; i < 12; i++)
ff_free_vlc(&ctx->studio_intra_tab[i]);
ff_free_vlc(&ctx->studio_luma_dc);
ff_free_vlc(&ctx->studio_chroma_dc);
}
return ff_h263_decode_end(avctx);
}
static const AVOption mpeg4_options[] = {
{"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{NULL}
};
static const AVClass mpeg4_class = {
.class_name = "MPEG4 Video Decoder",
.item_name = av_default_item_name,
.option = mpeg4_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_mpeg4_decoder = {
.name = "mpeg4",
.long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_MPEG4,
.priv_data_size = sizeof(Mpeg4DecContext),
.init = decode_init,
.close = decode_end,
.decode = ff_h263_decode_frame,
.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_FRAME_THREADS,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
.flush = ff_mpeg_flush,
.max_lowres = 3,
.pix_fmts = ff_h263_hwaccel_pixfmt_list_420,
.profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
.update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
.priv_class = &mpeg4_class,
.hw_configs = (const AVCodecHWConfigInternal*[]) {
#if CONFIG_MPEG4_NVDEC_HWACCEL
HWACCEL_NVDEC(mpeg4),
#endif
#if CONFIG_MPEG4_VAAPI_HWACCEL
HWACCEL_VAAPI(mpeg4),
#endif
#if CONFIG_MPEG4_VDPAU_HWACCEL
HWACCEL_VDPAU(mpeg4),
#endif
#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
HWACCEL_VIDEOTOOLBOX(mpeg4),
#endif
NULL
},
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_468_0 |
crossvul-cpp_data_bad_1357_0 | /*
* Copyright (c) 2018, SUSE LLC.
*
* This program is licensed under the BSD license, read LICENSE.BSD
* for further information
*/
/*
* repodata.c
*
* Manage data coming from one repository
*
* a repository can contain multiple repodata entries, consisting of
* different sets of keys and different sets of solvables
*/
#define _GNU_SOURCE
#include <string.h>
#include <fnmatch.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <regex.h>
#include "repo.h"
#include "pool.h"
#include "poolid_private.h"
#include "util.h"
#include "hash.h"
#include "chksum.h"
#include "repopack.h"
#include "repopage.h"
#ifdef _WIN32
#include "strfncs.h"
#endif
#define REPODATA_BLOCK 255
static unsigned char *data_skip_key(Repodata *data, unsigned char *dp, Repokey *key);
void
repodata_initdata(Repodata *data, Repo *repo, int localpool)
{
memset(data, 0, sizeof (*data));
data->repodataid = data - repo->repodata;
data->repo = repo;
data->localpool = localpool;
if (localpool)
stringpool_init_empty(&data->spool);
/* dirpool_init(&data->dirpool); just zeros out again */
data->keys = solv_calloc(1, sizeof(Repokey));
data->nkeys = 1;
data->schemata = solv_calloc(1, sizeof(Id));
data->schemadata = solv_calloc(1, sizeof(Id));
data->nschemata = 1;
data->schemadatalen = 1;
repopagestore_init(&data->store);
}
void
repodata_freedata(Repodata *data)
{
int i;
solv_free(data->keys);
solv_free(data->schemata);
solv_free(data->schemadata);
solv_free(data->schematahash);
stringpool_free(&data->spool);
dirpool_free(&data->dirpool);
solv_free(data->mainschemaoffsets);
solv_free(data->incoredata);
solv_free(data->incoreoffset);
solv_free(data->verticaloffset);
repopagestore_free(&data->store);
solv_free(data->vincore);
if (data->attrs)
for (i = 0; i < data->end - data->start; i++)
solv_free(data->attrs[i]);
solv_free(data->attrs);
if (data->xattrs)
for (i = 0; i < data->nxattrs; i++)
solv_free(data->xattrs[i]);
solv_free(data->xattrs);
solv_free(data->attrdata);
solv_free(data->attriddata);
solv_free(data->attrnum64data);
solv_free(data->dircache);
repodata_free_filelistfilter(data);
}
void
repodata_free(Repodata *data)
{
Repo *repo = data->repo;
int i = data - repo->repodata;
if (i == 0)
return;
repodata_freedata(data);
if (i < repo->nrepodata - 1)
{
/* whoa! this changes the repodataids! */
memmove(repo->repodata + i, repo->repodata + i + 1, (repo->nrepodata - 1 - i) * sizeof(Repodata));
for (; i < repo->nrepodata - 1; i++)
repo->repodata[i].repodataid = i;
}
repo->nrepodata--;
if (repo->nrepodata == 1)
{
repo->repodata = solv_free(repo->repodata);
repo->nrepodata = 0;
}
}
void
repodata_empty(Repodata *data, int localpool)
{
void (*loadcallback)(Repodata *) = data->loadcallback;
int state = data->state;
repodata_freedata(data);
repodata_initdata(data, data->repo, localpool);
data->state = state;
data->loadcallback = loadcallback;
}
/***************************************************************
* key pool management
*/
/* this is not so time critical that we need a hash, so we do a simple
* linear search */
Id
repodata_key2id(Repodata *data, Repokey *key, int create)
{
Id keyid;
for (keyid = 1; keyid < data->nkeys; keyid++)
if (data->keys[keyid].name == key->name && data->keys[keyid].type == key->type)
{
if ((key->type == REPOKEY_TYPE_CONSTANT || key->type == REPOKEY_TYPE_CONSTANTID) && key->size != data->keys[keyid].size)
continue;
break;
}
if (keyid == data->nkeys)
{
if (!create)
return 0;
/* allocate new key */
data->keys = solv_realloc2(data->keys, data->nkeys + 1, sizeof(Repokey));
data->keys[data->nkeys++] = *key;
if (data->verticaloffset)
{
data->verticaloffset = solv_realloc2(data->verticaloffset, data->nkeys, sizeof(Id));
data->verticaloffset[data->nkeys - 1] = 0;
}
data->keybits[(key->name >> 3) & (sizeof(data->keybits) - 1)] |= 1 << (key->name & 7);
}
return keyid;
}
/***************************************************************
* schema pool management
*/
#define SCHEMATA_BLOCK 31
#define SCHEMATADATA_BLOCK 255
Id
repodata_schema2id(Repodata *data, Id *schema, int create)
{
int h, len, i;
Id *sp, cid;
Id *schematahash;
if (!*schema)
return 0; /* XXX: allow empty schema? */
if ((schematahash = data->schematahash) == 0)
{
data->schematahash = schematahash = solv_calloc(256, sizeof(Id));
for (i = 1; i < data->nschemata; i++)
{
for (sp = data->schemadata + data->schemata[i], h = 0; *sp;)
h = h * 7 + *sp++;
h &= 255;
schematahash[h] = i;
}
data->schemadata = solv_extend_resize(data->schemadata, data->schemadatalen, sizeof(Id), SCHEMATADATA_BLOCK);
data->schemata = solv_extend_resize(data->schemata, data->nschemata, sizeof(Id), SCHEMATA_BLOCK);
}
for (sp = schema, len = 0, h = 0; *sp; len++)
h = h * 7 + *sp++;
h &= 255;
len++;
cid = schematahash[h];
if (cid)
{
if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))
return cid;
/* cache conflict, do a slow search */
for (cid = 1; cid < data->nschemata; cid++)
if (!memcmp(data->schemadata + data->schemata[cid], schema, len * sizeof(Id)))
return cid;
}
/* a new one */
if (!create)
return 0;
data->schemadata = solv_extend(data->schemadata, data->schemadatalen, len, sizeof(Id), SCHEMATADATA_BLOCK);
data->schemata = solv_extend(data->schemata, data->nschemata, 1, sizeof(Id), SCHEMATA_BLOCK);
/* add schema */
memcpy(data->schemadata + data->schemadatalen, schema, len * sizeof(Id));
data->schemata[data->nschemata] = data->schemadatalen;
data->schemadatalen += len;
schematahash[h] = data->nschemata;
#if 0
fprintf(stderr, "schema2id: new schema\n");
#endif
return data->nschemata++;
}
void
repodata_free_schemahash(Repodata *data)
{
data->schematahash = solv_free(data->schematahash);
/* shrink arrays */
data->schemata = solv_realloc2(data->schemata, data->nschemata, sizeof(Id));
data->schemadata = solv_realloc2(data->schemadata, data->schemadatalen, sizeof(Id));
}
/***************************************************************
* dir pool management
*/
#ifndef HAVE_STRCHRNUL
static inline const char *strchrnul(const char *str, char x)
{
const char *p = strchr(str, x);
return p ? p : str + strlen(str);
}
#endif
#define DIRCACHE_SIZE 41 /* < 1k */
#ifdef DIRCACHE_SIZE
struct dircache {
Id ids[DIRCACHE_SIZE];
char str[(DIRCACHE_SIZE * (DIRCACHE_SIZE - 1)) / 2];
};
#endif
Id
repodata_str2dir(Repodata *data, const char *dir, int create)
{
Id id, parent;
#ifdef DIRCACHE_SIZE
const char *dirs;
#endif
const char *dire;
if (!*dir)
return data->dirpool.ndirs ? 0 : dirpool_add_dir(&data->dirpool, 0, 0, create);
while (*dir == '/' && dir[1] == '/')
dir++;
if (*dir == '/' && !dir[1])
return data->dirpool.ndirs ? 1 : dirpool_add_dir(&data->dirpool, 0, 1, create);
parent = 0;
#ifdef DIRCACHE_SIZE
dirs = dir;
if (data->dircache)
{
int l;
struct dircache *dircache = data->dircache;
l = strlen(dir);
while (l > 0)
{
if (l < DIRCACHE_SIZE && dircache->ids[l] && !memcmp(dircache->str + l * (l - 1) / 2, dir, l))
{
parent = dircache->ids[l];
dir += l;
if (!*dir)
return parent;
while (*dir == '/')
dir++;
break;
}
while (--l)
if (dir[l] == '/')
break;
}
}
#endif
while (*dir)
{
dire = strchrnul(dir, '/');
if (data->localpool)
id = stringpool_strn2id(&data->spool, dir, dire - dir, create);
else
id = pool_strn2id(data->repo->pool, dir, dire - dir, create);
if (!id)
return 0;
parent = dirpool_add_dir(&data->dirpool, parent, id, create);
if (!parent)
return 0;
#ifdef DIRCACHE_SIZE
if (!data->dircache)
data->dircache = solv_calloc(1, sizeof(struct dircache));
if (data->dircache)
{
int l = dire - dirs;
if (l < DIRCACHE_SIZE)
{
data->dircache->ids[l] = parent;
memcpy(data->dircache->str + l * (l - 1) / 2, dirs, l);
}
}
#endif
if (!*dire)
break;
dir = dire + 1;
while (*dir == '/')
dir++;
}
return parent;
}
void
repodata_free_dircache(Repodata *data)
{
data->dircache = solv_free(data->dircache);
}
const char *
repodata_dir2str(Repodata *data, Id did, const char *suf)
{
Pool *pool = data->repo->pool;
int l = 0;
Id parent, comp;
const char *comps;
char *p;
if (!did)
return suf ? suf : "";
if (did == 1 && !suf)
return "/";
parent = did;
while (parent)
{
comp = dirpool_compid(&data->dirpool, parent);
comps = stringpool_id2str(data->localpool ? &data->spool : &pool->ss, comp);
l += strlen(comps);
parent = dirpool_parent(&data->dirpool, parent);
if (parent)
l++;
}
if (suf)
l += strlen(suf) + 1;
p = pool_alloctmpspace(pool, l + 1) + l;
*p = 0;
if (suf)
{
p -= strlen(suf);
strcpy(p, suf);
*--p = '/';
}
parent = did;
while (parent)
{
comp = dirpool_compid(&data->dirpool, parent);
comps = stringpool_id2str(data->localpool ? &data->spool : &pool->ss, comp);
l = strlen(comps);
p -= l;
strncpy(p, comps, l);
parent = dirpool_parent(&data->dirpool, parent);
if (parent)
*--p = '/';
}
return p;
}
/***************************************************************
* data management
*/
static inline unsigned char *
data_skip_schema(Repodata *data, unsigned char *dp, Id schema)
{
Id *keyp = data->schemadata + data->schemata[schema];
for (; *keyp; keyp++)
dp = data_skip_key(data, dp, data->keys + *keyp);
return dp;
}
static unsigned char *
data_skip_key(Repodata *data, unsigned char *dp, Repokey *key)
{
int nentries, schema;
switch(key->type)
{
case REPOKEY_TYPE_FIXARRAY:
dp = data_read_id(dp, &nentries);
if (!nentries)
return dp;
dp = data_read_id(dp, &schema);
while (nentries--)
dp = data_skip_schema(data, dp, schema);
return dp;
case REPOKEY_TYPE_FLEXARRAY:
dp = data_read_id(dp, &nentries);
while (nentries--)
{
dp = data_read_id(dp, &schema);
dp = data_skip_schema(data, dp, schema);
}
return dp;
default:
if (key->storage == KEY_STORAGE_INCORE)
dp = data_skip(dp, key->type);
else if (key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
dp = data_skip(dp, REPOKEY_TYPE_ID);
dp = data_skip(dp, REPOKEY_TYPE_ID);
}
return dp;
}
}
static unsigned char *
forward_to_key(Repodata *data, Id keyid, Id *keyp, unsigned char *dp)
{
Id k;
if (!keyid)
return 0;
if (data->mainschemaoffsets && dp == data->incoredata + data->mainschemaoffsets[0] && keyp == data->schemadata + data->schemata[data->mainschema])
{
int i;
for (i = 0; (k = *keyp++) != 0; i++)
if (k == keyid)
return data->incoredata + data->mainschemaoffsets[i];
return 0;
}
while ((k = *keyp++) != 0)
{
if (k == keyid)
return dp;
if (data->keys[k].storage == KEY_STORAGE_VERTICAL_OFFSET)
{
dp = data_skip(dp, REPOKEY_TYPE_ID); /* skip offset */
dp = data_skip(dp, REPOKEY_TYPE_ID); /* skip length */
continue;
}
if (data->keys[k].storage != KEY_STORAGE_INCORE)
continue;
dp = data_skip_key(data, dp, data->keys + k);
}
return 0;
}
static unsigned char *
get_vertical_data(Repodata *data, Repokey *key, Id off, Id len)
{
unsigned char *dp;
if (len <= 0)
return 0;
if (off >= data->lastverticaloffset)
{
off -= data->lastverticaloffset;
if ((unsigned int)off + len > data->vincorelen)
return 0;
return data->vincore + off;
}
if ((unsigned int)off + len > key->size)
return 0;
/* we now have the offset, go into vertical */
off += data->verticaloffset[key - data->keys];
/* fprintf(stderr, "key %d page %d\n", key->name, off / REPOPAGE_BLOBSIZE); */
dp = repopagestore_load_page_range(&data->store, off / REPOPAGE_BLOBSIZE, (off + len - 1) / REPOPAGE_BLOBSIZE);
data->storestate++;
if (dp)
dp += off % REPOPAGE_BLOBSIZE;
return dp;
}
static inline unsigned char *
get_data(Repodata *data, Repokey *key, unsigned char **dpp, int advance)
{
unsigned char *dp = *dpp;
if (!dp)
return 0;
if (key->storage == KEY_STORAGE_INCORE)
{
if (advance)
*dpp = data_skip_key(data, dp, key);
return dp;
}
else if (key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
Id off, len;
dp = data_read_id(dp, &off);
dp = data_read_id(dp, &len);
if (advance)
*dpp = dp;
return get_vertical_data(data, key, off, len);
}
return 0;
}
void
repodata_load(Repodata *data)
{
if (data->state != REPODATA_STUB)
return;
if (data->loadcallback)
data->loadcallback(data);
else
data->state = REPODATA_ERROR;
}
static int
maybe_load_repodata_stub(Repodata *data, Id keyname)
{
if (data->state != REPODATA_STUB)
{
data->state = REPODATA_ERROR;
return 0;
}
if (keyname)
{
int i;
for (i = 1; i < data->nkeys; i++)
if (keyname == data->keys[i].name)
break;
if (i == data->nkeys)
return 0;
}
repodata_load(data);
return data->state == REPODATA_AVAILABLE ? 1 : 0;
}
static inline int
maybe_load_repodata(Repodata *data, Id keyname)
{
if (keyname && !repodata_precheck_keyname(data, keyname))
return 0; /* do not bother... */
if (data->state == REPODATA_AVAILABLE || data->state == REPODATA_LOADING)
return 1;
if (data->state == REPODATA_ERROR)
return 0;
return maybe_load_repodata_stub(data, keyname);
}
static inline unsigned char *
solvid2data(Repodata *data, Id solvid, Id *schemap)
{
unsigned char *dp = data->incoredata;
if (!dp)
return 0;
if (solvid == SOLVID_META)
dp += 1; /* offset of "meta" solvable */
else if (solvid == SOLVID_POS)
{
Pool *pool = data->repo->pool;
if (data->repo != pool->pos.repo)
return 0;
if (data != data->repo->repodata + pool->pos.repodataid)
return 0;
dp += pool->pos.dp;
if (pool->pos.dp != 1)
{
*schemap = pool->pos.schema;
return dp;
}
}
else
{
if (solvid < data->start || solvid >= data->end)
return 0;
dp += data->incoreoffset[solvid - data->start];
}
return data_read_id(dp, schemap);
}
/************************************************************************
* data lookup
*/
static unsigned char *
find_key_data(Repodata *data, Id solvid, Id keyname, Repokey **keypp)
{
unsigned char *dp;
Id schema, *keyp, *kp;
Repokey *key;
if (!maybe_load_repodata(data, keyname))
return 0;
dp = solvid2data(data, solvid, &schema);
if (!dp)
return 0;
keyp = data->schemadata + data->schemata[schema];
for (kp = keyp; *kp; kp++)
if (data->keys[*kp].name == keyname)
break;
if (!*kp)
return 0;
*keypp = key = data->keys + *kp;
if (key->type == REPOKEY_TYPE_DELETED)
return 0;
if (key->type == REPOKEY_TYPE_VOID || key->type == REPOKEY_TYPE_CONSTANT || key->type == REPOKEY_TYPE_CONSTANTID)
return dp; /* no need to forward... */
if (key->storage != KEY_STORAGE_INCORE && key->storage != KEY_STORAGE_VERTICAL_OFFSET)
return 0; /* get_data will not work, no need to forward */
dp = forward_to_key(data, *kp, keyp, dp);
if (!dp)
return 0;
return get_data(data, key, &dp, 0);
}
static const Id *
repodata_lookup_schemakeys(Repodata *data, Id solvid)
{
Id schema;
if (!maybe_load_repodata(data, 0))
return 0;
if (!solvid2data(data, solvid, &schema))
return 0;
return data->schemadata + data->schemata[schema];
}
static Id *
alloc_keyskip()
{
Id *keyskip = solv_calloc(3 + 256, sizeof(Id));
keyskip[0] = 256;
keyskip[1] = keyskip[2] = 1;
return keyskip;
}
Id *
repodata_fill_keyskip(Repodata *data, Id solvid, Id *keyskip)
{
const Id *keyp;
Id maxkeyname, value;
keyp = repodata_lookup_schemakeys(data, solvid);
if (!keyp)
return keyskip; /* no keys for this solvid */
if (!keyskip)
keyskip = alloc_keyskip();
maxkeyname = keyskip[0];
value = keyskip[1] + data->repodataid;
for (; *keyp; keyp++)
{
Id keyname = data->keys[*keyp].name;
if (keyname >= maxkeyname)
{
int newmax = (keyname | 255) + 1;
keyskip = solv_realloc2(keyskip, 3 + newmax, sizeof(Id));
memset(keyskip + (3 + maxkeyname), 0, (newmax - maxkeyname) * sizeof(Id));
keyskip[0] = maxkeyname = newmax;
}
keyskip[3 + keyname] = value;
}
return keyskip;
}
Id
repodata_lookup_type(Repodata *data, Id solvid, Id keyname)
{
Id schema, *keyp, *kp;
if (!maybe_load_repodata(data, keyname))
return 0;
if (!solvid2data(data, solvid, &schema))
return 0;
keyp = data->schemadata + data->schemata[schema];
for (kp = keyp; *kp; kp++)
if (data->keys[*kp].name == keyname)
return data->keys[*kp].type;
return 0;
}
Id
repodata_lookup_id(Repodata *data, Id solvid, Id keyname)
{
unsigned char *dp;
Repokey *key;
Id id;
dp = find_key_data(data, solvid, keyname, &key);
if (!dp)
return 0;
if (key->type == REPOKEY_TYPE_CONSTANTID)
return key->size;
if (key->type != REPOKEY_TYPE_ID)
return 0;
dp = data_read_id(dp, &id);
return id;
}
const char *
repodata_lookup_str(Repodata *data, Id solvid, Id keyname)
{
unsigned char *dp;
Repokey *key;
Id id;
dp = find_key_data(data, solvid, keyname, &key);
if (!dp)
return 0;
if (key->type == REPOKEY_TYPE_STR)
return (const char *)dp;
if (key->type == REPOKEY_TYPE_CONSTANTID)
id = key->size;
else if (key->type == REPOKEY_TYPE_ID)
dp = data_read_id(dp, &id);
else
return 0;
if (data->localpool)
return stringpool_id2str(&data->spool, id);
return pool_id2str(data->repo->pool, id);
}
unsigned long long
repodata_lookup_num(Repodata *data, Id solvid, Id keyname, unsigned long long notfound)
{
unsigned char *dp;
Repokey *key;
unsigned int high, low;
dp = find_key_data(data, solvid, keyname, &key);
if (!dp)
return notfound;
switch (key->type)
{
case REPOKEY_TYPE_NUM:
data_read_num64(dp, &low, &high);
return (unsigned long long)high << 32 | low;
case REPOKEY_TYPE_CONSTANT:
return key->size;
default:
return notfound;
}
}
int
repodata_lookup_void(Repodata *data, Id solvid, Id keyname)
{
return repodata_lookup_type(data, solvid, keyname) == REPOKEY_TYPE_VOID ? 1 : 0;
}
const unsigned char *
repodata_lookup_bin_checksum(Repodata *data, Id solvid, Id keyname, Id *typep)
{
unsigned char *dp;
Repokey *key;
dp = find_key_data(data, solvid, keyname, &key);
if (!dp)
return 0;
switch (key->type)
{
case_CHKSUM_TYPES:
break;
default:
return 0;
}
*typep = key->type;
return dp;
}
int
repodata_lookup_idarray(Repodata *data, Id solvid, Id keyname, Queue *q)
{
unsigned char *dp;
Repokey *key;
Id id;
int eof = 0;
queue_empty(q);
dp = find_key_data(data, solvid, keyname, &key);
if (!dp)
return 0;
switch (key->type)
{
case REPOKEY_TYPE_CONSTANTID:
queue_push(q, key->size);
break;
case REPOKEY_TYPE_ID:
dp = data_read_id(dp, &id);
queue_push(q, id);
break;
case REPOKEY_TYPE_IDARRAY:
for (;;)
{
dp = data_read_ideof(dp, &id, &eof);
queue_push(q, id);
if (eof)
break;
}
break;
default:
return 0;
}
return 1;
}
const void *
repodata_lookup_binary(Repodata *data, Id solvid, Id keyname, int *lenp)
{
unsigned char *dp;
Repokey *key;
Id len;
dp = find_key_data(data, solvid, keyname, &key);
if (!dp || key->type != REPOKEY_TYPE_BINARY)
{
*lenp = 0;
return 0;
}
dp = data_read_id(dp, &len);
*lenp = len;
return dp;
}
/* highly specialized function to speed up fileprovides adding.
* - repodata must be available
* - solvid must be >= data->start and < data->end
* - returns NULL is not found, a "" entry if wrong type
* - also returns wrong type for REPOKEY_TYPE_DELETED
*/
const unsigned char *
repodata_lookup_packed_dirstrarray(Repodata *data, Id solvid, Id keyname)
{
static unsigned char wrongtype[2] = { 0x00 /* dir id 0 */, 0 /* "" */ };
unsigned char *dp;
Id schema, *keyp, *kp;
Repokey *key;
if (!data->incoredata || !data->incoreoffset[solvid - data->start])
return 0;
dp = data->incoredata + data->incoreoffset[solvid - data->start];
dp = data_read_id(dp, &schema);
keyp = data->schemadata + data->schemata[schema];
for (kp = keyp; *kp; kp++)
if (data->keys[*kp].name == keyname)
break;
if (!*kp)
return 0;
key = data->keys + *kp;
if (key->type != REPOKEY_TYPE_DIRSTRARRAY)
return wrongtype;
dp = forward_to_key(data, *kp, keyp, dp);
if (key->storage == KEY_STORAGE_INCORE)
return dp;
if (key->storage == KEY_STORAGE_VERTICAL_OFFSET && dp)
{
Id off, len;
dp = data_read_id(dp, &off);
data_read_id(dp, &len);
return get_vertical_data(data, key, off, len);
}
return 0;
}
/* id translation functions */
Id
repodata_globalize_id(Repodata *data, Id id, int create)
{
if (!id || !data || !data->localpool)
return id;
return pool_str2id(data->repo->pool, stringpool_id2str(&data->spool, id), create);
}
Id
repodata_localize_id(Repodata *data, Id id, int create)
{
if (!id || !data || !data->localpool)
return id;
return stringpool_str2id(&data->spool, pool_id2str(data->repo->pool, id), create);
}
Id
repodata_translate_id(Repodata *data, Repodata *fromdata, Id id, int create)
{
const char *s;
if (!id || !data || !fromdata)
return id;
if (data == fromdata || (!data->localpool && !fromdata->localpool))
return id;
if (fromdata->localpool)
s = stringpool_id2str(&fromdata->spool, id);
else
s = pool_id2str(data->repo->pool, id);
if (data->localpool)
return stringpool_str2id(&data->spool, s, create);
else
return pool_str2id(data->repo->pool, s, create);
}
Id
repodata_translate_dir_slow(Repodata *data, Repodata *fromdata, Id dir, int create, Id *cache)
{
Id parent, compid;
if (!dir)
{
/* make sure that the dirpool has an entry */
if (create && !data->dirpool.ndirs)
dirpool_add_dir(&data->dirpool, 0, 0, create);
return 0;
}
parent = dirpool_parent(&fromdata->dirpool, dir);
if (parent)
{
if (!(parent = repodata_translate_dir(data, fromdata, parent, create, cache)))
return 0;
}
compid = dirpool_compid(&fromdata->dirpool, dir);
if (compid > 1 && (data->localpool || fromdata->localpool))
{
if (!(compid = repodata_translate_id(data, fromdata, compid, create)))
return 0;
}
if (!(compid = dirpool_add_dir(&data->dirpool, parent, compid, create)))
return 0;
if (cache)
{
cache[(dir & 255) * 2] = dir;
cache[(dir & 255) * 2 + 1] = compid;
}
return compid;
}
/************************************************************************
* uninternalized lookup / search
*/
static void
data_fetch_uninternalized(Repodata *data, Repokey *key, Id value, KeyValue *kv)
{
Id *array;
kv->eof = 1;
switch (key->type)
{
case REPOKEY_TYPE_STR:
kv->str = (const char *)data->attrdata + value;
return;
case REPOKEY_TYPE_CONSTANT:
kv->num2 = 0;
kv->num = key->size;
return;
case REPOKEY_TYPE_CONSTANTID:
kv->id = key->size;
return;
case REPOKEY_TYPE_NUM:
kv->num2 = 0;
kv->num = value;
if (value & 0x80000000)
{
kv->num = (unsigned int)data->attrnum64data[value ^ 0x80000000];
kv->num2 = (unsigned int)(data->attrnum64data[value ^ 0x80000000] >> 32);
}
return;
case_CHKSUM_TYPES:
kv->num = 0; /* not stringified */
kv->str = (const char *)data->attrdata + value;
return;
case REPOKEY_TYPE_BINARY:
kv->str = (const char *)data_read_id(data->attrdata + value, (Id *)&kv->num);
return;
case REPOKEY_TYPE_IDARRAY:
array = data->attriddata + (value + kv->entry);
kv->id = array[0];
kv->eof = array[1] ? 0 : 1;
return;
case REPOKEY_TYPE_DIRSTRARRAY:
kv->num = 0; /* not stringified */
array = data->attriddata + (value + kv->entry * 2);
kv->id = array[0];
kv->str = (const char *)data->attrdata + array[1];
kv->eof = array[2] ? 0 : 1;
return;
case REPOKEY_TYPE_DIRNUMNUMARRAY:
array = data->attriddata + (value + kv->entry * 3);
kv->id = array[0];
kv->num = array[1];
kv->num2 = array[2];
kv->eof = array[3] ? 0 : 1;
return;
case REPOKEY_TYPE_FIXARRAY:
case REPOKEY_TYPE_FLEXARRAY:
array = data->attriddata + (value + kv->entry);
kv->id = array[0]; /* the handle */
kv->eof = array[1] ? 0 : 1;
return;
default:
kv->id = value;
return;
}
}
Repokey *
repodata_lookup_kv_uninternalized(Repodata *data, Id solvid, Id keyname, KeyValue *kv)
{
Id *ap;
if (!data->attrs || solvid < data->start || solvid >= data->end)
return 0;
ap = data->attrs[solvid - data->start];
if (!ap)
return 0;
for (; *ap; ap += 2)
{
Repokey *key = data->keys + *ap;
if (key->name != keyname)
continue;
data_fetch_uninternalized(data, key, ap[1], kv);
return key;
}
return 0;
}
void
repodata_search_uninternalized(Repodata *data, Id solvid, Id keyname, int flags, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata)
{
Id *ap;
int stop;
Solvable *s;
KeyValue kv;
if (!data->attrs || solvid < data->start || solvid >= data->end)
return;
ap = data->attrs[solvid - data->start];
if (!ap)
return;
for (; *ap; ap += 2)
{
Repokey *key = data->keys + *ap;
if (keyname && key->name != keyname)
continue;
s = solvid > 0 ? data->repo->pool->solvables + solvid : 0;
kv.entry = 0;
do
{
data_fetch_uninternalized(data, key, ap[1], &kv);
stop = callback(cbdata, s, data, key, &kv);
kv.entry++;
}
while (!kv.eof && !stop);
if (keyname || stop > SEARCH_NEXT_KEY)
return;
}
}
/************************************************************************
* data search
*/
const char *
repodata_stringify(Pool *pool, Repodata *data, Repokey *key, KeyValue *kv, int flags)
{
switch (key->type)
{
case REPOKEY_TYPE_ID:
case REPOKEY_TYPE_CONSTANTID:
case REPOKEY_TYPE_IDARRAY:
if (data && data->localpool)
kv->str = stringpool_id2str(&data->spool, kv->id);
else
kv->str = pool_id2str(pool, kv->id);
if ((flags & SEARCH_SKIP_KIND) != 0 && key->storage == KEY_STORAGE_SOLVABLE && (key->name == SOLVABLE_NAME || key->type == REPOKEY_TYPE_IDARRAY))
{
const char *s;
for (s = kv->str; *s >= 'a' && *s <= 'z'; s++)
;
if (*s == ':' && s > kv->str)
kv->str = s + 1;
}
return kv->str;
case REPOKEY_TYPE_STR:
return kv->str;
case REPOKEY_TYPE_DIRSTRARRAY:
if (!(flags & SEARCH_FILES))
return kv->str; /* match just the basename */
if (kv->num)
return kv->str; /* already stringified */
/* Put the full filename into kv->str. */
kv->str = repodata_dir2str(data, kv->id, kv->str);
kv->num = 1; /* mark stringification */
return kv->str;
case_CHKSUM_TYPES:
if (!(flags & SEARCH_CHECKSUMS))
return 0; /* skip em */
if (kv->num)
return kv->str; /* already stringified */
kv->str = repodata_chk2str(data, key->type, (const unsigned char *)kv->str);
kv->num = 1; /* mark stringification */
return kv->str;
default:
return 0;
}
}
/* this is an internal hack to pass the parent kv to repodata_search_keyskip */
struct subschema_data {
void *cbdata;
Id solvid;
KeyValue *parent;
};
void
repodata_search_arrayelement(Repodata *data, Id solvid, Id keyname, int flags, KeyValue *kv, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata)
{
repodata_search_keyskip(data, solvid, keyname, flags | SEARCH_SUBSCHEMA, (Id *)kv, callback, cbdata);
}
static int
repodata_search_array(Repodata *data, Id solvid, Id keyname, int flags, Repokey *key, KeyValue *kv, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata)
{
Solvable *s = solvid > 0 ? data->repo->pool->solvables + solvid : 0;
unsigned char *dp = (unsigned char *)kv->str;
int stop;
Id schema = 0;
if (!dp || kv->entry != -1)
return 0;
while (++kv->entry < (int)kv->num)
{
if (kv->entry)
dp = data_skip_schema(data, dp, schema);
if (kv->entry == 0 || key->type == REPOKEY_TYPE_FLEXARRAY)
dp = data_read_id(dp, &schema);
kv->id = schema;
kv->str = (const char *)dp;
kv->eof = kv->entry == kv->num - 1 ? 1 : 0;
stop = callback(cbdata, s, data, key, kv);
if (stop && stop != SEARCH_ENTERSUB)
return stop;
if ((flags & SEARCH_SUB) != 0 || stop == SEARCH_ENTERSUB)
repodata_search_keyskip(data, solvid, keyname, flags | SEARCH_SUBSCHEMA, (Id *)kv, callback, cbdata);
}
if ((flags & SEARCH_ARRAYSENTINEL) != 0)
{
if (kv->entry)
dp = data_skip_schema(data, dp, schema);
kv->id = 0;
kv->str = (const char *)dp;
kv->eof = 2;
return callback(cbdata, s, data, key, kv);
}
return 0;
}
/* search a specific repodata */
void
repodata_search_keyskip(Repodata *data, Id solvid, Id keyname, int flags, Id *keyskip, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata)
{
Id schema;
Repokey *key;
Id keyid, *kp, *keyp;
unsigned char *dp, *ddp;
int onekey = 0;
int stop;
KeyValue kv;
Solvable *s;
if (!maybe_load_repodata(data, keyname))
return;
if ((flags & SEARCH_SUBSCHEMA) != 0)
{
flags ^= SEARCH_SUBSCHEMA;
kv.parent = (KeyValue *)keyskip;
keyskip = 0;
schema = kv.parent->id;
dp = (unsigned char *)kv.parent->str;
}
else
{
schema = 0;
dp = solvid2data(data, solvid, &schema);
if (!dp)
return;
kv.parent = 0;
}
s = solvid > 0 ? data->repo->pool->solvables + solvid : 0;
keyp = data->schemadata + data->schemata[schema];
if (keyname)
{
/* search for a specific key */
for (kp = keyp; *kp; kp++)
if (data->keys[*kp].name == keyname)
break;
if (!*kp)
return;
dp = forward_to_key(data, *kp, keyp, dp);
if (!dp)
return;
keyp = kp;
onekey = 1;
}
while ((keyid = *keyp++) != 0)
{
stop = 0;
key = data->keys + keyid;
ddp = get_data(data, key, &dp, *keyp && !onekey ? 1 : 0);
if (keyskip && (key->name >= keyskip[0] || keyskip[3 + key->name] != keyskip[1] + data->repodataid))
{
if (onekey)
return;
continue;
}
if (key->type == REPOKEY_TYPE_DELETED && !(flags & SEARCH_KEEP_TYPE_DELETED))
{
if (onekey)
return;
continue;
}
if (key->type == REPOKEY_TYPE_FLEXARRAY || key->type == REPOKEY_TYPE_FIXARRAY)
{
kv.entry = -1;
ddp = data_read_id(ddp, (Id *)&kv.num);
kv.str = (const char *)ddp;
stop = repodata_search_array(data, solvid, 0, flags, key, &kv, callback, cbdata);
if (onekey || stop > SEARCH_NEXT_KEY)
return;
continue;
}
kv.entry = 0;
do
{
ddp = data_fetch(ddp, &kv, key);
if (!ddp)
break;
stop = callback(cbdata, s, data, key, &kv);
kv.entry++;
}
while (!kv.eof && !stop);
if (onekey || stop > SEARCH_NEXT_KEY)
return;
}
}
void
repodata_search(Repodata *data, Id solvid, Id keyname, int flags, int (*callback)(void *cbdata, Solvable *s, Repodata *data, Repokey *key, KeyValue *kv), void *cbdata)
{
repodata_search_keyskip(data, solvid, keyname, flags, 0, callback, cbdata);
}
void
repodata_setpos_kv(Repodata *data, KeyValue *kv)
{
Pool *pool = data->repo->pool;
if (!kv)
pool_clear_pos(pool);
else
{
pool->pos.repo = data->repo;
pool->pos.repodataid = data - data->repo->repodata;
pool->pos.dp = (unsigned char *)kv->str - data->incoredata;
pool->pos.schema = kv->id;
}
}
/************************************************************************
* data iterator functions
*/
static inline Id *
solvabledata_fetch(Solvable *s, KeyValue *kv, Id keyname)
{
kv->id = keyname;
switch (keyname)
{
case SOLVABLE_NAME:
kv->eof = 1;
return &s->name;
case SOLVABLE_ARCH:
kv->eof = 1;
return &s->arch;
case SOLVABLE_EVR:
kv->eof = 1;
return &s->evr;
case SOLVABLE_VENDOR:
kv->eof = 1;
return &s->vendor;
case SOLVABLE_PROVIDES:
kv->eof = 0;
return s->provides ? s->repo->idarraydata + s->provides : 0;
case SOLVABLE_OBSOLETES:
kv->eof = 0;
return s->obsoletes ? s->repo->idarraydata + s->obsoletes : 0;
case SOLVABLE_CONFLICTS:
kv->eof = 0;
return s->conflicts ? s->repo->idarraydata + s->conflicts : 0;
case SOLVABLE_REQUIRES:
kv->eof = 0;
return s->requires ? s->repo->idarraydata + s->requires : 0;
case SOLVABLE_RECOMMENDS:
kv->eof = 0;
return s->recommends ? s->repo->idarraydata + s->recommends : 0;
case SOLVABLE_SUPPLEMENTS:
kv->eof = 0;
return s->supplements ? s->repo->idarraydata + s->supplements : 0;
case SOLVABLE_SUGGESTS:
kv->eof = 0;
return s->suggests ? s->repo->idarraydata + s->suggests : 0;
case SOLVABLE_ENHANCES:
kv->eof = 0;
return s->enhances ? s->repo->idarraydata + s->enhances : 0;
case RPM_RPMDBID:
kv->eof = 1;
return s->repo->rpmdbid ? s->repo->rpmdbid + (s - s->repo->pool->solvables - s->repo->start) : 0;
default:
return 0;
}
}
int
datamatcher_init(Datamatcher *ma, const char *match, int flags)
{
match = match ? solv_strdup(match) : 0;
ma->match = match;
ma->flags = flags;
ma->error = 0;
ma->matchdata = 0;
if ((flags & SEARCH_STRINGMASK) == SEARCH_REGEX)
{
ma->matchdata = solv_calloc(1, sizeof(regex_t));
ma->error = regcomp((regex_t *)ma->matchdata, match, REG_EXTENDED | REG_NOSUB | REG_NEWLINE | ((flags & SEARCH_NOCASE) ? REG_ICASE : 0));
if (ma->error)
{
solv_free(ma->matchdata);
ma->flags = (flags & ~SEARCH_STRINGMASK) | SEARCH_ERROR;
}
}
if ((flags & SEARCH_FILES) != 0 && match)
{
/* prepare basename check */
if ((flags & SEARCH_STRINGMASK) == SEARCH_STRING || (flags & SEARCH_STRINGMASK) == SEARCH_STRINGEND)
{
const char *p = strrchr(match, '/');
ma->matchdata = (void *)(p ? p + 1 : match);
}
else if ((flags & SEARCH_STRINGMASK) == SEARCH_GLOB)
{
const char *p;
for (p = match + strlen(match) - 1; p >= match; p--)
if (*p == '[' || *p == ']' || *p == '*' || *p == '?' || *p == '/')
break;
ma->matchdata = (void *)(p + 1);
}
}
return ma->error;
}
void
datamatcher_free(Datamatcher *ma)
{
if (ma->match)
ma->match = solv_free((char *)ma->match);
if ((ma->flags & SEARCH_STRINGMASK) == SEARCH_REGEX && ma->matchdata)
{
regfree(ma->matchdata);
solv_free(ma->matchdata);
}
ma->matchdata = 0;
}
int
datamatcher_match(Datamatcher *ma, const char *str)
{
int l;
switch ((ma->flags & SEARCH_STRINGMASK))
{
case SEARCH_SUBSTRING:
if (ma->flags & SEARCH_NOCASE)
return strcasestr(str, ma->match) != 0;
else
return strstr(str, ma->match) != 0;
case SEARCH_STRING:
if (ma->flags & SEARCH_NOCASE)
return !strcasecmp(ma->match, str);
else
return !strcmp(ma->match, str);
case SEARCH_STRINGSTART:
if (ma->flags & SEARCH_NOCASE)
return !strncasecmp(ma->match, str, strlen(ma->match));
else
return !strncmp(ma->match, str, strlen(ma->match));
case SEARCH_STRINGEND:
l = strlen(str) - strlen(ma->match);
if (l < 0)
return 0;
if (ma->flags & SEARCH_NOCASE)
return !strcasecmp(ma->match, str + l);
else
return !strcmp(ma->match, str + l);
case SEARCH_GLOB:
return !fnmatch(ma->match, str, (ma->flags & SEARCH_NOCASE) ? FNM_CASEFOLD : 0);
case SEARCH_REGEX:
return !regexec((const regex_t *)ma->matchdata, str, 0, NULL, 0);
default:
return 0;
}
}
/* check if the matcher can match the provides basename */
int
datamatcher_checkbasename(Datamatcher *ma, const char *basename)
{
int l;
const char *match = ma->matchdata;
if (!match)
return 1;
switch (ma->flags & SEARCH_STRINGMASK)
{
case SEARCH_STRING:
break;
case SEARCH_STRINGEND:
if (match != ma->match)
break; /* had slash, do exact match on basename */
/* FALLTHROUGH */
case SEARCH_GLOB:
/* check if the basename ends with match */
l = strlen(basename) - strlen(match);
if (l < 0)
return 0;
basename += l;
break;
default:
return 1; /* maybe matches */
}
if ((ma->flags & SEARCH_NOCASE) != 0)
return !strcasecmp(match, basename);
else
return !strcmp(match, basename);
}
enum {
di_bye,
di_enterrepo,
di_entersolvable,
di_enterrepodata,
di_enterschema,
di_enterkey,
di_nextattr,
di_nextkey,
di_nextrepodata,
di_nextsolvable,
di_nextrepo,
di_enterarray,
di_nextarrayelement,
di_entersub,
di_leavesub,
di_nextsolvablekey,
di_entersolvablekey,
di_nextsolvableattr
};
/* see dataiterator.h for documentation */
int
dataiterator_init(Dataiterator *di, Pool *pool, Repo *repo, Id p, Id keyname, const char *match, int flags)
{
memset(di, 0, sizeof(*di));
di->pool = pool;
di->flags = flags & ~SEARCH_THISSOLVID;
if (!pool || (repo && repo->pool != pool))
{
di->state = di_bye;
return -1;
}
if (match)
{
int error;
if ((error = datamatcher_init(&di->matcher, match, flags)) != 0)
{
di->state = di_bye;
return error;
}
}
di->keyname = keyname;
di->keynames[0] = keyname;
dataiterator_set_search(di, repo, p);
return 0;
}
void
dataiterator_init_clone(Dataiterator *di, Dataiterator *from)
{
*di = *from;
if (di->dupstr)
{
if (di->dupstr == di->kv.str)
di->dupstr = solv_memdup(di->dupstr, di->dupstrn);
else
{
di->dupstr = 0;
di->dupstrn = 0;
}
}
memset(&di->matcher, 0, sizeof(di->matcher));
if (from->matcher.match)
datamatcher_init(&di->matcher, from->matcher.match, from->matcher.flags);
if (di->nparents)
{
/* fix pointers */
int i;
for (i = 1; i < di->nparents; i++)
di->parents[i].kv.parent = &di->parents[i - 1].kv;
di->kv.parent = &di->parents[di->nparents - 1].kv;
}
if (di->oldkeyskip)
di->oldkeyskip = solv_memdup2(di->oldkeyskip, 3 + di->oldkeyskip[0], sizeof(Id));
if (di->keyskip)
di->keyskip = di->oldkeyskip;
}
int
dataiterator_set_match(Dataiterator *di, const char *match, int flags)
{
di->flags = (flags & ~SEARCH_THISSOLVID) | (di->flags & SEARCH_THISSOLVID);
datamatcher_free(&di->matcher);
memset(&di->matcher, 0, sizeof(di->matcher));
if (match)
{
int error;
if ((error = datamatcher_init(&di->matcher, match, flags)) != 0)
{
di->state = di_bye;
return error;
}
}
return 0;
}
void
dataiterator_set_search(Dataiterator *di, Repo *repo, Id p)
{
di->repo = repo;
di->repoid = 0;
di->flags &= ~SEARCH_THISSOLVID;
di->nparents = 0;
di->rootlevel = 0;
di->repodataid = 1;
if (!di->pool->urepos)
{
di->state = di_bye;
return;
}
if (!repo)
{
di->repoid = 1;
di->repo = di->pool->repos[di->repoid];
}
di->state = di_enterrepo;
if (p)
dataiterator_jump_to_solvid(di, p);
}
void
dataiterator_set_keyname(Dataiterator *di, Id keyname)
{
di->nkeynames = 0;
di->keyname = keyname;
di->keynames[0] = keyname;
}
void
dataiterator_prepend_keyname(Dataiterator *di, Id keyname)
{
int i;
if (di->nkeynames >= sizeof(di->keynames)/sizeof(*di->keynames) - 2)
{
di->state = di_bye; /* sorry */
return;
}
for (i = di->nkeynames + 1; i > 0; i--)
di->keynames[i] = di->keynames[i - 1];
di->keynames[0] = di->keyname = keyname;
di->nkeynames++;
}
void
dataiterator_free(Dataiterator *di)
{
if (di->matcher.match)
datamatcher_free(&di->matcher);
if (di->dupstr)
solv_free(di->dupstr);
if (di->oldkeyskip)
solv_free(di->oldkeyskip);
}
static unsigned char *
dataiterator_find_keyname(Dataiterator *di, Id keyname)
{
Id *keyp;
Repokey *keys = di->data->keys, *key;
unsigned char *dp;
for (keyp = di->keyp; *keyp; keyp++)
if (keys[*keyp].name == keyname)
break;
if (!*keyp)
return 0;
key = keys + *keyp;
if (key->type == REPOKEY_TYPE_DELETED)
return 0;
if (key->storage != KEY_STORAGE_INCORE && key->storage != KEY_STORAGE_VERTICAL_OFFSET)
return 0; /* get_data will not work, no need to forward */
dp = forward_to_key(di->data, *keyp, di->keyp, di->dp);
if (!dp)
return 0;
di->keyp = keyp;
return dp;
}
int
dataiterator_step(Dataiterator *di)
{
Id schema;
if (di->state == di_nextattr && di->key->storage == KEY_STORAGE_VERTICAL_OFFSET && di->vert_ddp && di->vert_storestate != di->data->storestate)
{
unsigned int ddpoff = di->ddp - di->vert_ddp;
di->vert_off += ddpoff;
di->vert_len -= ddpoff;
di->ddp = di->vert_ddp = get_vertical_data(di->data, di->key, di->vert_off, di->vert_len);
di->vert_storestate = di->data->storestate;
if (!di->ddp)
di->state = di_nextkey;
}
for (;;)
{
switch (di->state)
{
case di_enterrepo: di_enterrepo:
if (!di->repo || (di->repo->disabled && !(di->flags & SEARCH_DISABLED_REPOS)))
goto di_nextrepo;
if (!(di->flags & SEARCH_THISSOLVID))
{
di->solvid = di->repo->start - 1; /* reset solvid iterator */
goto di_nextsolvable;
}
/* FALLTHROUGH */
case di_entersolvable: di_entersolvable:
if (!di->repodataid)
goto di_enterrepodata; /* POS case, repodata is set */
if (di->solvid > 0 && !(di->flags & SEARCH_NO_STORAGE_SOLVABLE) && (!di->keyname || (di->keyname >= SOLVABLE_NAME && di->keyname <= RPM_RPMDBID)) && di->nparents - di->rootlevel == di->nkeynames)
{
extern Repokey repo_solvablekeys[RPM_RPMDBID - SOLVABLE_NAME + 1];
di->key = repo_solvablekeys + (di->keyname ? di->keyname - SOLVABLE_NAME : 0);
di->data = 0;
goto di_entersolvablekey;
}
if (di->keyname)
{
di->data = di->keyname == SOLVABLE_FILELIST ? repo_lookup_filelist_repodata(di->repo, di->solvid, &di->matcher) : repo_lookup_repodata_opt(di->repo, di->solvid, di->keyname);
if (!di->data)
goto di_nextsolvable;
di->repodataid = di->data - di->repo->repodata;
di->keyskip = 0;
goto di_enterrepodata;
}
di_leavesolvablekey:
di->repodataid = 1; /* reset repodata iterator */
di->keyskip = repo_create_keyskip(di->repo, di->solvid, &di->oldkeyskip);
/* FALLTHROUGH */
case di_enterrepodata: di_enterrepodata:
if (di->repodataid)
{
if (di->repodataid >= di->repo->nrepodata)
goto di_nextsolvable;
di->data = di->repo->repodata + di->repodataid;
}
if (!maybe_load_repodata(di->data, di->keyname))
goto di_nextrepodata;
di->dp = solvid2data(di->data, di->solvid, &schema);
if (!di->dp)
goto di_nextrepodata;
if (di->solvid == SOLVID_POS)
di->solvid = di->pool->pos.solvid;
/* reset key iterator */
di->keyp = di->data->schemadata + di->data->schemata[schema];
/* FALLTHROUGH */
case di_enterschema: di_enterschema:
if (di->keyname)
di->dp = dataiterator_find_keyname(di, di->keyname);
if (!di->dp || !*di->keyp)
{
if (di->kv.parent)
goto di_leavesub;
goto di_nextrepodata;
}
/* FALLTHROUGH */
case di_enterkey: di_enterkey:
di->kv.entry = -1;
di->key = di->data->keys + *di->keyp;
if (!di->dp)
goto di_nextkey;
/* this is get_data() modified to store vert_ data */
if (di->key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
Id off, len;
di->dp = data_read_id(di->dp, &off);
di->dp = data_read_id(di->dp, &len);
di->vert_ddp = di->ddp = get_vertical_data(di->data, di->key, off, len);
di->vert_off = off;
di->vert_len = len;
di->vert_storestate = di->data->storestate;
}
else if (di->key->storage == KEY_STORAGE_INCORE)
{
di->ddp = di->dp; /* start of data */
if (di->keyp[1] && (!di->keyname || (di->flags & SEARCH_SUB) != 0))
di->dp = data_skip_key(di->data, di->dp, di->key); /* advance to next key */
}
else
di->ddp = 0;
if (!di->ddp)
goto di_nextkey;
if (di->keyskip && (di->key->name >= di->keyskip[0] || di->keyskip[3 + di->key->name] != di->keyskip[1] + di->data->repodataid))
goto di_nextkey;
if (di->key->type == REPOKEY_TYPE_DELETED && !(di->flags & SEARCH_KEEP_TYPE_DELETED))
goto di_nextkey;
if (di->key->type == REPOKEY_TYPE_FIXARRAY || di->key->type == REPOKEY_TYPE_FLEXARRAY)
goto di_enterarray;
if (di->nkeynames && di->nparents - di->rootlevel < di->nkeynames)
goto di_nextkey;
/* FALLTHROUGH */
case di_nextattr:
di->kv.entry++;
di->ddp = data_fetch(di->ddp, &di->kv, di->key);
di->state = di->kv.eof ? di_nextkey : di_nextattr;
break;
case di_nextkey: di_nextkey:
if (!di->keyname && *++di->keyp)
goto di_enterkey;
if (di->kv.parent)
goto di_leavesub;
/* FALLTHROUGH */
case di_nextrepodata: di_nextrepodata:
if (!di->keyname && di->repodataid && ++di->repodataid < di->repo->nrepodata)
goto di_enterrepodata;
/* FALLTHROUGH */
case di_nextsolvable: di_nextsolvable:
if (!(di->flags & SEARCH_THISSOLVID))
{
if (di->solvid < 0)
di->solvid = di->repo->start;
else
di->solvid++;
for (; di->solvid < di->repo->end; di->solvid++)
{
if (di->pool->solvables[di->solvid].repo == di->repo)
goto di_entersolvable;
}
}
/* FALLTHROUGH */
case di_nextrepo: di_nextrepo:
if (di->repoid > 0)
{
di->repoid++;
di->repodataid = 1;
if (di->repoid < di->pool->nrepos)
{
di->repo = di->pool->repos[di->repoid];
goto di_enterrepo;
}
}
/* FALLTHROUGH */
case di_bye: di_bye:
di->state = di_bye;
return 0;
case di_enterarray: di_enterarray:
if (di->key->name == REPOSITORY_SOLVABLES)
goto di_nextkey;
di->ddp = data_read_id(di->ddp, (Id *)&di->kv.num);
di->kv.eof = 0;
di->kv.entry = -1;
/* FALLTHROUGH */
case di_nextarrayelement: di_nextarrayelement:
di->kv.entry++;
if (di->kv.entry)
di->ddp = data_skip_schema(di->data, di->ddp, di->kv.id);
if (di->kv.entry == di->kv.num)
{
if (di->nkeynames && di->nparents - di->rootlevel < di->nkeynames)
goto di_nextkey;
if (!(di->flags & SEARCH_ARRAYSENTINEL))
goto di_nextkey;
di->kv.str = (char *)di->ddp;
di->kv.eof = 2;
di->state = di_nextkey;
break;
}
if (di->kv.entry == di->kv.num - 1)
di->kv.eof = 1;
if (di->key->type == REPOKEY_TYPE_FLEXARRAY || !di->kv.entry)
di->ddp = data_read_id(di->ddp, &di->kv.id);
di->kv.str = (char *)di->ddp;
if (di->nkeynames && di->nparents - di->rootlevel < di->nkeynames)
goto di_entersub;
if ((di->flags & SEARCH_SUB) != 0)
di->state = di_entersub;
else
di->state = di_nextarrayelement;
break;
case di_entersub: di_entersub:
if (di->nparents == sizeof(di->parents)/sizeof(*di->parents) - 1)
goto di_nextarrayelement; /* sorry, full */
di->parents[di->nparents].kv = di->kv;
di->parents[di->nparents].dp = di->dp;
di->parents[di->nparents].keyp = di->keyp;
di->dp = (unsigned char *)di->kv.str;
di->keyp = di->data->schemadata + di->data->schemata[di->kv.id];
memset(&di->kv, 0, sizeof(di->kv));
di->kv.parent = &di->parents[di->nparents].kv;
di->nparents++;
di->keyname = di->keynames[di->nparents - di->rootlevel];
goto di_enterschema;
case di_leavesub: di_leavesub:
if (di->nparents - 1 < di->rootlevel)
goto di_bye;
di->nparents--;
di->dp = di->parents[di->nparents].dp;
di->kv = di->parents[di->nparents].kv;
di->keyp = di->parents[di->nparents].keyp;
di->key = di->data->keys + *di->keyp;
di->ddp = (unsigned char *)di->kv.str;
di->keyname = di->keynames[di->nparents - di->rootlevel];
goto di_nextarrayelement;
/* special solvable attr handling follows */
case di_nextsolvablekey: di_nextsolvablekey:
if (di->keyname)
goto di_nextsolvable;
if (di->key->name == RPM_RPMDBID) /* reached end of list? */
goto di_leavesolvablekey;
di->key++;
/* FALLTHROUGH */
case di_entersolvablekey: di_entersolvablekey:
di->idp = solvabledata_fetch(di->pool->solvables + di->solvid, &di->kv, di->key->name);
if (!di->idp || !*di->idp)
goto di_nextsolvablekey;
if (di->kv.eof)
{
/* not an array */
di->kv.id = *di->idp;
di->kv.num = *di->idp; /* for rpmdbid */
di->kv.num2 = 0; /* for rpmdbid */
di->kv.entry = 0;
di->state = di_nextsolvablekey;
break;
}
di->kv.entry = -1;
/* FALLTHROUGH */
case di_nextsolvableattr:
di->state = di_nextsolvableattr;
di->kv.id = *di->idp++;
di->kv.entry++;
if (!*di->idp)
{
di->kv.eof = 1;
di->state = di_nextsolvablekey;
}
break;
}
/* we have a potential match */
if (di->matcher.match)
{
const char *str;
/* simple pre-check so that we don't need to stringify */
if (di->keyname == SOLVABLE_FILELIST && di->key->type == REPOKEY_TYPE_DIRSTRARRAY && (di->matcher.flags & SEARCH_FILES) != 0)
if (!datamatcher_checkbasename(&di->matcher, di->kv.str))
continue;
/* now stringify so that we can do the matching */
if (!(str = repodata_stringify(di->pool, di->data, di->key, &di->kv, di->flags)))
{
if (di->keyname && (di->key->type == REPOKEY_TYPE_FIXARRAY || di->key->type == REPOKEY_TYPE_FLEXARRAY))
return 1;
continue;
}
if (!datamatcher_match(&di->matcher, str))
continue;
}
else
{
/* stringify filelist if requested */
if (di->keyname == SOLVABLE_FILELIST && di->key->type == REPOKEY_TYPE_DIRSTRARRAY && (di->flags & SEARCH_FILES) != 0)
repodata_stringify(di->pool, di->data, di->key, &di->kv, di->flags);
}
/* found something! */
return 1;
}
}
void
dataiterator_entersub(Dataiterator *di)
{
if (di->state == di_nextarrayelement)
di->state = di_entersub;
}
void
dataiterator_setpos(Dataiterator *di)
{
if (di->kv.eof == 2)
{
pool_clear_pos(di->pool);
return;
}
di->pool->pos.solvid = di->solvid;
di->pool->pos.repo = di->repo;
di->pool->pos.repodataid = di->data - di->repo->repodata;
di->pool->pos.schema = di->kv.id;
di->pool->pos.dp = (unsigned char *)di->kv.str - di->data->incoredata;
}
void
dataiterator_setpos_parent(Dataiterator *di)
{
if (!di->kv.parent || di->kv.parent->eof == 2)
{
pool_clear_pos(di->pool);
return;
}
di->pool->pos.solvid = di->solvid;
di->pool->pos.repo = di->repo;
di->pool->pos.repodataid = di->data - di->repo->repodata;
di->pool->pos.schema = di->kv.parent->id;
di->pool->pos.dp = (unsigned char *)di->kv.parent->str - di->data->incoredata;
}
/* clones just the position, not the search keys/matcher */
void
dataiterator_clonepos(Dataiterator *di, Dataiterator *from)
{
di->state = from->state;
di->flags &= ~SEARCH_THISSOLVID;
di->flags |= (from->flags & SEARCH_THISSOLVID);
di->repo = from->repo;
di->data = from->data;
di->dp = from->dp;
di->ddp = from->ddp;
di->idp = from->idp;
di->keyp = from->keyp;
di->key = from->key;
di->kv = from->kv;
di->repodataid = from->repodataid;
di->solvid = from->solvid;
di->repoid = from->repoid;
di->rootlevel = from->rootlevel;
memcpy(di->parents, from->parents, sizeof(from->parents));
di->nparents = from->nparents;
if (di->nparents)
{
int i;
for (i = 1; i < di->nparents; i++)
di->parents[i].kv.parent = &di->parents[i - 1].kv;
di->kv.parent = &di->parents[di->nparents - 1].kv;
}
di->dupstr = 0;
di->dupstrn = 0;
if (from->dupstr && from->dupstr == from->kv.str)
{
di->dupstrn = from->dupstrn;
di->dupstr = solv_memdup(from->dupstr, from->dupstrn);
}
}
void
dataiterator_seek(Dataiterator *di, int whence)
{
if ((whence & DI_SEEK_STAY) != 0)
di->rootlevel = di->nparents;
switch (whence & ~DI_SEEK_STAY)
{
case DI_SEEK_CHILD:
if (di->state != di_nextarrayelement)
break;
if ((whence & DI_SEEK_STAY) != 0)
di->rootlevel = di->nparents + 1; /* XXX: dangerous! */
di->state = di_entersub;
break;
case DI_SEEK_PARENT:
if (!di->nparents)
{
di->state = di_bye;
break;
}
di->nparents--;
if (di->rootlevel > di->nparents)
di->rootlevel = di->nparents;
di->dp = di->parents[di->nparents].dp;
di->kv = di->parents[di->nparents].kv;
di->keyp = di->parents[di->nparents].keyp;
di->key = di->data->keys + *di->keyp;
di->ddp = (unsigned char *)di->kv.str;
di->keyname = di->keynames[di->nparents - di->rootlevel];
di->state = di_nextarrayelement;
break;
case DI_SEEK_REWIND:
if (!di->nparents)
{
di->state = di_bye;
break;
}
di->dp = (unsigned char *)di->kv.parent->str;
di->keyp = di->data->schemadata + di->data->schemata[di->kv.parent->id];
di->state = di_enterschema;
break;
default:
break;
}
}
void
dataiterator_skip_attribute(Dataiterator *di)
{
if (di->state == di_nextsolvableattr)
di->state = di_nextsolvablekey;
else
di->state = di_nextkey;
}
void
dataiterator_skip_solvable(Dataiterator *di)
{
di->nparents = 0;
di->kv.parent = 0;
di->rootlevel = 0;
di->keyname = di->keynames[0];
di->state = di_nextsolvable;
}
void
dataiterator_skip_repo(Dataiterator *di)
{
di->nparents = 0;
di->kv.parent = 0;
di->rootlevel = 0;
di->keyname = di->keynames[0];
di->state = di_nextrepo;
}
void
dataiterator_jump_to_solvid(Dataiterator *di, Id solvid)
{
di->nparents = 0;
di->kv.parent = 0;
di->rootlevel = 0;
di->keyname = di->keynames[0];
if (solvid == SOLVID_POS)
{
di->repo = di->pool->pos.repo;
if (!di->repo)
{
di->state = di_bye;
return;
}
di->repoid = 0;
if (!di->pool->pos.repodataid && di->pool->pos.solvid == SOLVID_META) {
solvid = SOLVID_META; /* META pos hack */
} else {
di->data = di->repo->repodata + di->pool->pos.repodataid;
di->repodataid = 0;
}
}
else if (solvid > 0)
{
di->repo = di->pool->solvables[solvid].repo;
di->repoid = 0;
}
if (di->repoid > 0)
{
if (!di->pool->urepos)
{
di->state = di_bye;
return;
}
di->repoid = 1;
di->repo = di->pool->repos[di->repoid];
}
if (solvid != SOLVID_POS)
di->repodataid = 1;
di->solvid = solvid;
if (solvid)
di->flags |= SEARCH_THISSOLVID;
di->state = di_enterrepo;
}
void
dataiterator_jump_to_repo(Dataiterator *di, Repo *repo)
{
di->nparents = 0;
di->kv.parent = 0;
di->rootlevel = 0;
di->repo = repo;
di->repoid = 0; /* 0 means stay at repo */
di->repodataid = 1;
di->solvid = 0;
di->flags &= ~SEARCH_THISSOLVID;
di->state = di_enterrepo;
}
int
dataiterator_match(Dataiterator *di, Datamatcher *ma)
{
const char *str;
if (!(str = repodata_stringify(di->pool, di->data, di->key, &di->kv, di->flags)))
return 0;
return ma ? datamatcher_match(ma, str) : 1;
}
void
dataiterator_strdup(Dataiterator *di)
{
int l = -1;
if (!di->kv.str || di->kv.str == di->dupstr)
return;
switch (di->key->type)
{
case_CHKSUM_TYPES:
case REPOKEY_TYPE_DIRSTRARRAY:
if (di->kv.num) /* was it stringified into tmp space? */
l = strlen(di->kv.str) + 1;
break;
default:
break;
}
if (l < 0 && di->key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
switch (di->key->type)
{
case REPOKEY_TYPE_STR:
case REPOKEY_TYPE_DIRSTRARRAY:
l = strlen(di->kv.str) + 1;
break;
case_CHKSUM_TYPES:
l = solv_chksum_len(di->key->type);
break;
case REPOKEY_TYPE_BINARY:
l = di->kv.num;
break;
}
}
if (l >= 0)
{
if (!di->dupstrn || di->dupstrn < l)
{
di->dupstrn = l + 16;
di->dupstr = solv_realloc(di->dupstr, di->dupstrn);
}
if (l)
memcpy(di->dupstr, di->kv.str, l);
di->kv.str = di->dupstr;
}
}
/************************************************************************
* data modify functions
*/
/* extend repodata so that it includes solvables p */
void
repodata_extend(Repodata *data, Id p)
{
if (data->start == data->end)
data->start = data->end = p;
if (p >= data->end)
{
int old = data->end - data->start;
int new = p - data->end + 1;
if (data->attrs)
{
data->attrs = solv_extend(data->attrs, old, new, sizeof(Id *), REPODATA_BLOCK);
memset(data->attrs + old, 0, new * sizeof(Id *));
}
data->incoreoffset = solv_extend(data->incoreoffset, old, new, sizeof(Id), REPODATA_BLOCK);
memset(data->incoreoffset + old, 0, new * sizeof(Id));
data->end = p + 1;
}
if (p < data->start)
{
int old = data->end - data->start;
int new = data->start - p;
if (data->attrs)
{
data->attrs = solv_extend_resize(data->attrs, old + new, sizeof(Id *), REPODATA_BLOCK);
memmove(data->attrs + new, data->attrs, old * sizeof(Id *));
memset(data->attrs, 0, new * sizeof(Id *));
}
data->incoreoffset = solv_extend_resize(data->incoreoffset, old + new, sizeof(Id), REPODATA_BLOCK);
memmove(data->incoreoffset + new, data->incoreoffset, old * sizeof(Id));
memset(data->incoreoffset, 0, new * sizeof(Id));
data->start = p;
}
}
/* shrink end of repodata */
void
repodata_shrink(Repodata *data, int end)
{
int i;
if (data->end <= end)
return;
if (data->start >= end)
{
if (data->attrs)
{
for (i = 0; i < data->end - data->start; i++)
solv_free(data->attrs[i]);
data->attrs = solv_free(data->attrs);
}
data->incoreoffset = solv_free(data->incoreoffset);
data->start = data->end = 0;
return;
}
if (data->attrs)
{
for (i = end; i < data->end; i++)
solv_free(data->attrs[i - data->start]);
data->attrs = solv_extend_resize(data->attrs, end - data->start, sizeof(Id *), REPODATA_BLOCK);
}
if (data->incoreoffset)
data->incoreoffset = solv_extend_resize(data->incoreoffset, end - data->start, sizeof(Id), REPODATA_BLOCK);
data->end = end;
}
/* extend repodata so that it includes solvables from start to start + num - 1 */
void
repodata_extend_block(Repodata *data, Id start, Id num)
{
if (!num)
return;
if (!data->incoreoffset)
{
/* this also means that data->attrs is NULL */
data->incoreoffset = solv_calloc_block(num, sizeof(Id), REPODATA_BLOCK);
data->start = start;
data->end = start + num;
return;
}
repodata_extend(data, start);
if (num > 1)
repodata_extend(data, start + num - 1);
}
/**********************************************************************/
#define REPODATA_ATTRS_BLOCK 31
#define REPODATA_ATTRDATA_BLOCK 1023
#define REPODATA_ATTRIDDATA_BLOCK 63
#define REPODATA_ATTRNUM64DATA_BLOCK 15
Id
repodata_new_handle(Repodata *data)
{
if (!data->nxattrs)
{
data->xattrs = solv_calloc_block(1, sizeof(Id *), REPODATA_BLOCK);
data->nxattrs = 2; /* -1: SOLVID_META */
}
data->xattrs = solv_extend(data->xattrs, data->nxattrs, 1, sizeof(Id *), REPODATA_BLOCK);
data->xattrs[data->nxattrs] = 0;
return -(data->nxattrs++);
}
static inline Id **
repodata_get_attrp(Repodata *data, Id handle)
{
if (handle < 0)
{
if (handle == SOLVID_META && !data->xattrs)
{
data->xattrs = solv_calloc_block(1, sizeof(Id *), REPODATA_BLOCK);
data->nxattrs = 2;
}
return data->xattrs - handle;
}
if (handle < data->start || handle >= data->end)
repodata_extend(data, handle);
if (!data->attrs)
data->attrs = solv_calloc_block(data->end - data->start, sizeof(Id *), REPODATA_BLOCK);
return data->attrs + (handle - data->start);
}
static void
repodata_insert_keyid(Repodata *data, Id handle, Id keyid, Id val, int overwrite)
{
Id *pp;
Id *ap, **app;
int i;
app = repodata_get_attrp(data, handle);
ap = *app;
i = 0;
if (ap)
{
/* Determine equality based on the name only, allows us to change
type (when overwrite is set), and makes TYPE_CONSTANT work. */
for (pp = ap; *pp; pp += 2)
if (data->keys[*pp].name == data->keys[keyid].name)
break;
if (*pp)
{
if (overwrite || data->keys[*pp].type == REPOKEY_TYPE_DELETED)
{
pp[0] = keyid;
pp[1] = val;
}
return;
}
i = pp - ap;
}
ap = solv_extend(ap, i, 3, sizeof(Id), REPODATA_ATTRS_BLOCK);
*app = ap;
pp = ap + i;
*pp++ = keyid;
*pp++ = val;
*pp = 0;
}
static void
repodata_set(Repodata *data, Id solvid, Repokey *key, Id val)
{
Id keyid;
keyid = repodata_key2id(data, key, 1);
repodata_insert_keyid(data, solvid, keyid, val, 1);
}
void
repodata_set_id(Repodata *data, Id solvid, Id keyname, Id id)
{
Repokey key;
key.name = keyname;
key.type = REPOKEY_TYPE_ID;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, id);
}
void
repodata_set_num(Repodata *data, Id solvid, Id keyname, unsigned long long num)
{
Repokey key;
key.name = keyname;
key.type = REPOKEY_TYPE_NUM;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
if (num >= 0x80000000)
{
data->attrnum64data = solv_extend(data->attrnum64data, data->attrnum64datalen, 1, sizeof(unsigned long long), REPODATA_ATTRNUM64DATA_BLOCK);
data->attrnum64data[data->attrnum64datalen] = num;
num = 0x80000000 | data->attrnum64datalen++;
}
repodata_set(data, solvid, &key, (Id)num);
}
void
repodata_set_poolstr(Repodata *data, Id solvid, Id keyname, const char *str)
{
Repokey key;
Id id;
if (data->localpool)
id = stringpool_str2id(&data->spool, str, 1);
else
id = pool_str2id(data->repo->pool, str, 1);
key.name = keyname;
key.type = REPOKEY_TYPE_ID;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, id);
}
void
repodata_set_constant(Repodata *data, Id solvid, Id keyname, unsigned int constant)
{
Repokey key;
key.name = keyname;
key.type = REPOKEY_TYPE_CONSTANT;
key.size = constant;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, 0);
}
void
repodata_set_constantid(Repodata *data, Id solvid, Id keyname, Id id)
{
Repokey key;
key.name = keyname;
key.type = REPOKEY_TYPE_CONSTANTID;
key.size = id;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, 0);
}
void
repodata_set_void(Repodata *data, Id solvid, Id keyname)
{
Repokey key;
key.name = keyname;
key.type = REPOKEY_TYPE_VOID;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, 0);
}
void
repodata_set_str(Repodata *data, Id solvid, Id keyname, const char *str)
{
Repokey key;
int l;
l = strlen(str) + 1;
key.name = keyname;
key.type = REPOKEY_TYPE_STR;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
data->attrdata = solv_extend(data->attrdata, data->attrdatalen, l, 1, REPODATA_ATTRDATA_BLOCK);
memcpy(data->attrdata + data->attrdatalen, str, l);
repodata_set(data, solvid, &key, data->attrdatalen);
data->attrdatalen += l;
}
void
repodata_set_binary(Repodata *data, Id solvid, Id keyname, void *buf, int len)
{
Repokey key;
unsigned char *dp;
if (len < 0)
return;
key.name = keyname;
key.type = REPOKEY_TYPE_BINARY;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
data->attrdata = solv_extend(data->attrdata, data->attrdatalen, len + 5, 1, REPODATA_ATTRDATA_BLOCK);
dp = data->attrdata + data->attrdatalen;
if (len >= (1 << 14))
{
if (len >= (1 << 28))
*dp++ = (len >> 28) | 128;
if (len >= (1 << 21))
*dp++ = (len >> 21) | 128;
*dp++ = (len >> 14) | 128;
}
if (len >= (1 << 7))
*dp++ = (len >> 7) | 128;
*dp++ = len & 127;
if (len)
memcpy(dp, buf, len);
repodata_set(data, solvid, &key, data->attrdatalen);
data->attrdatalen = dp + len - data->attrdata;
}
/* add an array element consisting of entrysize Ids to the repodata. modifies attriddata
* so that the caller can append entrysize new elements plus the termination zero there */
static void
repodata_add_array(Repodata *data, Id handle, Id keyname, Id keytype, int entrysize)
{
int oldsize;
Id *ida, *pp, **ppp;
/* check if it is the same as last time, this speeds things up a lot */
if (handle == data->lasthandle && data->keys[data->lastkey].name == keyname && data->keys[data->lastkey].type == keytype && data->attriddatalen == data->lastdatalen)
{
/* great! just append the new data */
data->attriddata = solv_extend(data->attriddata, data->attriddatalen, entrysize, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK);
data->attriddatalen--; /* overwrite terminating 0 */
data->lastdatalen += entrysize;
return;
}
ppp = repodata_get_attrp(data, handle);
pp = *ppp;
if (pp)
{
for (; *pp; pp += 2)
if (data->keys[*pp].name == keyname)
break;
}
if (!pp || !*pp || data->keys[*pp].type != keytype)
{
/* not found. allocate new key */
Repokey key;
Id keyid;
key.name = keyname;
key.type = keytype;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
data->attriddata = solv_extend(data->attriddata, data->attriddatalen, entrysize + 1, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK);
keyid = repodata_key2id(data, &key, 1);
repodata_insert_keyid(data, handle, keyid, data->attriddatalen, 1);
data->lasthandle = handle;
data->lastkey = keyid;
data->lastdatalen = data->attriddatalen + entrysize + 1;
return;
}
oldsize = 0;
for (ida = data->attriddata + pp[1]; *ida; ida += entrysize)
oldsize += entrysize;
if (ida + 1 == data->attriddata + data->attriddatalen)
{
/* this was the last entry, just append it */
data->attriddata = solv_extend(data->attriddata, data->attriddatalen, entrysize, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK);
data->attriddatalen--; /* overwrite terminating 0 */
}
else
{
/* too bad. move to back. */
data->attriddata = solv_extend(data->attriddata, data->attriddatalen, oldsize + entrysize + 1, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK);
memcpy(data->attriddata + data->attriddatalen, data->attriddata + pp[1], oldsize * sizeof(Id));
pp[1] = data->attriddatalen;
data->attriddatalen += oldsize;
}
data->lasthandle = handle;
data->lastkey = *pp;
data->lastdatalen = data->attriddatalen + entrysize + 1;
}
void
repodata_set_bin_checksum(Repodata *data, Id solvid, Id keyname, Id type,
const unsigned char *str)
{
Repokey key;
int l;
if (!(l = solv_chksum_len(type)))
return;
key.name = keyname;
key.type = type;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
data->attrdata = solv_extend(data->attrdata, data->attrdatalen, l, 1, REPODATA_ATTRDATA_BLOCK);
memcpy(data->attrdata + data->attrdatalen, str, l);
repodata_set(data, solvid, &key, data->attrdatalen);
data->attrdatalen += l;
}
void
repodata_set_checksum(Repodata *data, Id solvid, Id keyname, Id type,
const char *str)
{
unsigned char buf[64];
int l;
if (!(l = solv_chksum_len(type)))
return;
if (l > sizeof(buf) || solv_hex2bin(&str, buf, l) != l)
return;
repodata_set_bin_checksum(data, solvid, keyname, type, buf);
}
const char *
repodata_chk2str(Repodata *data, Id type, const unsigned char *buf)
{
int l;
if (!(l = solv_chksum_len(type)))
return "";
return pool_bin2hex(data->repo->pool, buf, l);
}
/* rpm filenames don't contain the epoch, so strip it */
static inline const char *
evrid2vrstr(Pool *pool, Id evrid)
{
const char *p, *evr = pool_id2str(pool, evrid);
if (!evr)
return evr;
for (p = evr; *p >= '0' && *p <= '9'; p++)
;
return p != evr && *p == ':' && p[1] ? p + 1 : evr;
}
static inline void
repodata_set_poolstrn(Repodata *data, Id solvid, Id keyname, const char *str, int l)
{
Id id;
if (data->localpool)
id = stringpool_strn2id(&data->spool, str, l, 1);
else
id = pool_strn2id(data->repo->pool, str, l, 1);
repodata_set_id(data, solvid, keyname, id);
}
static inline void
repodata_set_strn(Repodata *data, Id solvid, Id keyname, const char *str, int l)
{
if (!str[l])
repodata_set_str(data, solvid, keyname, str);
else
{
char *s = solv_strdup(str);
s[l] = 0;
repodata_set_str(data, solvid, keyname, s);
free(s);
}
}
void
repodata_set_location(Repodata *data, Id solvid, int medianr, const char *dir, const char *file)
{
Pool *pool = data->repo->pool;
Solvable *s;
const char *str, *fp;
int l = 0;
if (medianr)
repodata_set_constant(data, solvid, SOLVABLE_MEDIANR, medianr);
if (!dir)
{
if ((dir = strrchr(file, '/')) != 0)
{
l = dir - file;
dir = file;
file = dir + l + 1;
if (!l)
l++;
}
}
else
l = strlen(dir);
if (l >= 2 && dir[0] == '.' && dir[1] == '/' && (l == 2 || dir[2] != '/'))
{
dir += 2;
l -= 2;
}
if (l == 1 && dir[0] == '.')
l = 0;
s = pool->solvables + solvid;
if (dir && l)
{
str = pool_id2str(pool, s->arch);
if (!strncmp(dir, str, l) && !str[l])
repodata_set_void(data, solvid, SOLVABLE_MEDIADIR);
else
repodata_set_strn(data, solvid, SOLVABLE_MEDIADIR, dir, l);
}
fp = file;
str = pool_id2str(pool, s->name);
l = strlen(str);
if ((!l || !strncmp(fp, str, l)) && fp[l] == '-')
{
fp += l + 1;
str = evrid2vrstr(pool, s->evr);
l = strlen(str);
if ((!l || !strncmp(fp, str, l)) && fp[l] == '.')
{
fp += l + 1;
str = pool_id2str(pool, s->arch);
l = strlen(str);
if ((!l || !strncmp(fp, str, l)) && !strcmp(fp + l, ".rpm"))
{
repodata_set_void(data, solvid, SOLVABLE_MEDIAFILE);
return;
}
}
}
repodata_set_str(data, solvid, SOLVABLE_MEDIAFILE, file);
}
/* XXX: medianr is currently not stored */
void
repodata_set_deltalocation(Repodata *data, Id handle, int medianr, const char *dir, const char *file)
{
int l = 0;
const char *evr, *suf, *s;
if (!dir)
{
if ((dir = strrchr(file, '/')) != 0)
{
l = dir - file;
dir = file;
file = dir + l + 1;
if (!l)
l++;
}
}
else
l = strlen(dir);
if (l >= 2 && dir[0] == '.' && dir[1] == '/' && (l == 2 || dir[2] != '/'))
{
dir += 2;
l -= 2;
}
if (l == 1 && dir[0] == '.')
l = 0;
if (dir && l)
repodata_set_poolstrn(data, handle, DELTA_LOCATION_DIR, dir, l);
evr = strchr(file, '-');
if (evr)
{
for (s = evr - 1; s > file; s--)
if (*s == '-')
{
evr = s;
break;
}
}
suf = strrchr(file, '.');
if (suf)
{
for (s = suf - 1; s > file; s--)
if (*s == '.')
{
suf = s;
break;
}
if (!strcmp(suf, ".delta.rpm") || !strcmp(suf, ".patch.rpm"))
{
/* We accept one more item as suffix. */
for (s = suf - 1; s > file; s--)
if (*s == '.')
{
suf = s;
break;
}
}
}
if (!evr)
suf = 0;
if (suf && evr && suf < evr)
suf = 0;
repodata_set_poolstrn(data, handle, DELTA_LOCATION_NAME, file, evr ? evr - file : strlen(file));
if (evr)
repodata_set_poolstrn(data, handle, DELTA_LOCATION_EVR, evr + 1, suf ? suf - evr - 1: strlen(evr + 1));
if (suf)
repodata_set_poolstr(data, handle, DELTA_LOCATION_SUFFIX, suf + 1);
}
void
repodata_set_sourcepkg(Repodata *data, Id solvid, const char *sourcepkg)
{
Pool *pool = data->repo->pool;
Solvable *s = pool->solvables + solvid;
const char *p, *sevr, *sarch, *name, *evr;
p = strrchr(sourcepkg, '.');
if (!p || strcmp(p, ".rpm") != 0)
{
if (*sourcepkg)
repodata_set_str(data, solvid, SOLVABLE_SOURCENAME, sourcepkg);
return;
}
p--;
while (p > sourcepkg && *p != '.')
p--;
if (*p != '.' || p == sourcepkg)
return;
sarch = p-- + 1;
while (p > sourcepkg && *p != '-')
p--;
if (*p != '-' || p == sourcepkg)
return;
p--;
while (p > sourcepkg && *p != '-')
p--;
if (*p != '-' || p == sourcepkg)
return;
sevr = p + 1;
pool = s->repo->pool;
name = pool_id2str(pool, s->name);
if (name && !strncmp(sourcepkg, name, sevr - sourcepkg - 1) && name[sevr - sourcepkg - 1] == 0)
repodata_set_void(data, solvid, SOLVABLE_SOURCENAME);
else
repodata_set_id(data, solvid, SOLVABLE_SOURCENAME, pool_strn2id(pool, sourcepkg, sevr - sourcepkg - 1, 1));
evr = evrid2vrstr(pool, s->evr);
if (evr && !strncmp(sevr, evr, sarch - sevr - 1) && evr[sarch - sevr - 1] == 0)
repodata_set_void(data, solvid, SOLVABLE_SOURCEEVR);
else
repodata_set_id(data, solvid, SOLVABLE_SOURCEEVR, pool_strn2id(pool, sevr, sarch - sevr - 1, 1));
if (!strcmp(sarch, "src.rpm"))
repodata_set_constantid(data, solvid, SOLVABLE_SOURCEARCH, ARCH_SRC);
else if (!strcmp(sarch, "nosrc.rpm"))
repodata_set_constantid(data, solvid, SOLVABLE_SOURCEARCH, ARCH_NOSRC);
else
repodata_set_constantid(data, solvid, SOLVABLE_SOURCEARCH, pool_strn2id(pool, sarch, strlen(sarch) - 4, 1));
}
void
repodata_set_idarray(Repodata *data, Id solvid, Id keyname, Queue *q)
{
Repokey key;
int i;
key.name = keyname;
key.type = REPOKEY_TYPE_IDARRAY;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, data->attriddatalen);
data->attriddata = solv_extend(data->attriddata, data->attriddatalen, q->count + 1, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK);
for (i = 0; i < q->count; i++)
data->attriddata[data->attriddatalen++] = q->elements[i];
data->attriddata[data->attriddatalen++] = 0;
}
void
repodata_add_dirnumnum(Repodata *data, Id solvid, Id keyname, Id dir, Id num, Id num2)
{
assert(dir);
#if 0
fprintf(stderr, "repodata_add_dirnumnum %d %d %d %d (%d)\n", solvid, dir, num, num2, data->attriddatalen);
#endif
repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_DIRNUMNUMARRAY, 3);
data->attriddata[data->attriddatalen++] = dir;
data->attriddata[data->attriddatalen++] = num;
data->attriddata[data->attriddatalen++] = num2;
data->attriddata[data->attriddatalen++] = 0;
}
void
repodata_add_dirstr(Repodata *data, Id solvid, Id keyname, Id dir, const char *str)
{
Id stroff;
int l;
assert(dir);
l = strlen(str) + 1;
data->attrdata = solv_extend(data->attrdata, data->attrdatalen, l, 1, REPODATA_ATTRDATA_BLOCK);
memcpy(data->attrdata + data->attrdatalen, str, l);
stroff = data->attrdatalen;
data->attrdatalen += l;
#if 0
fprintf(stderr, "repodata_add_dirstr %d %d %s (%d)\n", solvid, dir, str, data->attriddatalen);
#endif
repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_DIRSTRARRAY, 2);
data->attriddata[data->attriddatalen++] = dir;
data->attriddata[data->attriddatalen++] = stroff;
data->attriddata[data->attriddatalen++] = 0;
}
void
repodata_add_idarray(Repodata *data, Id solvid, Id keyname, Id id)
{
#if 0
fprintf(stderr, "repodata_add_idarray %d %d (%d)\n", solvid, id, data->attriddatalen);
#endif
repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_IDARRAY, 1);
data->attriddata[data->attriddatalen++] = id;
data->attriddata[data->attriddatalen++] = 0;
}
void
repodata_add_poolstr_array(Repodata *data, Id solvid, Id keyname,
const char *str)
{
Id id;
if (data->localpool)
id = stringpool_str2id(&data->spool, str, 1);
else
id = pool_str2id(data->repo->pool, str, 1);
repodata_add_idarray(data, solvid, keyname, id);
}
void
repodata_add_fixarray(Repodata *data, Id solvid, Id keyname, Id handle)
{
repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_FIXARRAY, 1);
data->attriddata[data->attriddatalen++] = handle;
data->attriddata[data->attriddatalen++] = 0;
}
void
repodata_add_flexarray(Repodata *data, Id solvid, Id keyname, Id handle)
{
repodata_add_array(data, solvid, keyname, REPOKEY_TYPE_FLEXARRAY, 1);
data->attriddata[data->attriddatalen++] = handle;
data->attriddata[data->attriddatalen++] = 0;
}
void
repodata_set_kv(Repodata *data, Id solvid, Id keyname, Id keytype, KeyValue *kv)
{
switch (keytype)
{
case REPOKEY_TYPE_ID:
repodata_set_id(data, solvid, keyname, kv->id);
break;
case REPOKEY_TYPE_CONSTANTID:
repodata_set_constantid(data, solvid, keyname, kv->id);
break;
case REPOKEY_TYPE_IDARRAY:
repodata_add_idarray(data, solvid, keyname, kv->id);
break;
case REPOKEY_TYPE_STR:
repodata_set_str(data, solvid, keyname, kv->str);
break;
case REPOKEY_TYPE_VOID:
repodata_set_void(data, solvid, keyname);
break;
case REPOKEY_TYPE_NUM:
repodata_set_num(data, solvid, keyname, SOLV_KV_NUM64(kv));
break;
case REPOKEY_TYPE_CONSTANT:
repodata_set_constant(data, solvid, keyname, kv->num);
break;
case REPOKEY_TYPE_DIRNUMNUMARRAY:
if (kv->id)
repodata_add_dirnumnum(data, solvid, keyname, kv->id, kv->num, kv->num2);
break;
case REPOKEY_TYPE_DIRSTRARRAY:
repodata_add_dirstr(data, solvid, keyname, kv->id, kv->str);
break;
case_CHKSUM_TYPES:
repodata_set_bin_checksum(data, solvid, keyname, keytype, (const unsigned char *)kv->str);
break;
default:
break;
}
}
void
repodata_unset_uninternalized(Repodata *data, Id solvid, Id keyname)
{
Id *pp, *ap, **app;
app = repodata_get_attrp(data, solvid);
ap = *app;
if (!ap)
return;
if (!keyname)
{
*app = 0; /* delete all attributes */
return;
}
for (; *ap; ap += 2)
if (data->keys[*ap].name == keyname)
break;
if (!*ap)
return;
pp = ap;
ap += 2;
for (; *ap; ap += 2)
{
if (data->keys[*ap].name == keyname)
continue;
*pp++ = ap[0];
*pp++ = ap[1];
}
*pp = 0;
}
void
repodata_unset(Repodata *data, Id solvid, Id keyname)
{
Repokey key;
key.name = keyname;
key.type = REPOKEY_TYPE_DELETED;
key.size = 0;
key.storage = KEY_STORAGE_INCORE;
repodata_set(data, solvid, &key, 0);
}
/* add all (uninternalized) attrs from src to dest */
void
repodata_merge_attrs(Repodata *data, Id dest, Id src)
{
Id *keyp;
if (dest == src || !data->attrs || !(keyp = data->attrs[src - data->start]))
return;
for (; *keyp; keyp += 2)
repodata_insert_keyid(data, dest, keyp[0], keyp[1], 0);
}
/* add some (uninternalized) attrs from src to dest */
void
repodata_merge_some_attrs(Repodata *data, Id dest, Id src, Map *keyidmap, int overwrite)
{
Id *keyp;
if (dest == src || !data->attrs || !(keyp = data->attrs[src - data->start]))
return;
for (; *keyp; keyp += 2)
if (!keyidmap || MAPTST(keyidmap, keyp[0]))
repodata_insert_keyid(data, dest, keyp[0], keyp[1], overwrite);
}
/* swap (uninternalized) attrs from src and dest */
void
repodata_swap_attrs(Repodata *data, Id dest, Id src)
{
Id *tmpattrs;
if (!data->attrs || dest == src)
return;
if (dest < data->start || dest >= data->end)
repodata_extend(data, dest);
if (src < data->start || src >= data->end)
repodata_extend(data, src);
tmpattrs = data->attrs[dest - data->start];
data->attrs[dest - data->start] = data->attrs[src - data->start];
data->attrs[src - data->start] = tmpattrs;
}
/**********************************************************************/
/* TODO: unify with repo_write and repo_solv! */
#define EXTDATA_BLOCK 1023
struct extdata {
unsigned char *buf;
int len;
};
static void
data_addid(struct extdata *xd, Id sx)
{
unsigned int x = (unsigned int)sx;
unsigned char *dp;
xd->buf = solv_extend(xd->buf, xd->len, 5, 1, EXTDATA_BLOCK);
dp = xd->buf + xd->len;
if (x >= (1 << 14))
{
if (x >= (1 << 28))
*dp++ = (x >> 28) | 128;
if (x >= (1 << 21))
*dp++ = (x >> 21) | 128;
*dp++ = (x >> 14) | 128;
}
if (x >= (1 << 7))
*dp++ = (x >> 7) | 128;
*dp++ = x & 127;
xd->len = dp - xd->buf;
}
static void
data_addid64(struct extdata *xd, unsigned long long x)
{
if (x >= 0x100000000)
{
if ((x >> 35) != 0)
{
data_addid(xd, (Id)(x >> 35));
xd->buf[xd->len - 1] |= 128;
}
data_addid(xd, (Id)((unsigned int)x | 0x80000000));
xd->buf[xd->len - 5] = (x >> 28) | 128;
}
else
data_addid(xd, (Id)x);
}
static void
data_addideof(struct extdata *xd, Id sx, int eof)
{
unsigned int x = (unsigned int)sx;
unsigned char *dp;
xd->buf = solv_extend(xd->buf, xd->len, 5, 1, EXTDATA_BLOCK);
dp = xd->buf + xd->len;
if (x >= (1 << 13))
{
if (x >= (1 << 27))
*dp++ = (x >> 27) | 128;
if (x >= (1 << 20))
*dp++ = (x >> 20) | 128;
*dp++ = (x >> 13) | 128;
}
if (x >= (1 << 6))
*dp++ = (x >> 6) | 128;
*dp++ = eof ? (x & 63) : (x & 63) | 64;
xd->len = dp - xd->buf;
}
static void
data_addblob(struct extdata *xd, unsigned char *blob, int len)
{
xd->buf = solv_extend(xd->buf, xd->len, len, 1, EXTDATA_BLOCK);
memcpy(xd->buf + xd->len, blob, len);
xd->len += len;
}
/*********************************/
/* this is to reduct memory usage when internalizing oversized repos */
static void
compact_attrdata(Repodata *data, int entry, int nentry)
{
int i;
unsigned int attrdatastart = data->attrdatalen;
unsigned int attriddatastart = data->attriddatalen;
if (attrdatastart < 1024 * 1024 * 4 && attriddatastart < 1024 * 1024)
return;
for (i = entry; i < nentry; i++)
{
Id v, *attrs = data->attrs[i];
if (!attrs)
continue;
for (; *attrs; attrs += 2)
{
switch (data->keys[*attrs].type)
{
case REPOKEY_TYPE_STR:
case REPOKEY_TYPE_BINARY:
case_CHKSUM_TYPES:
if ((unsigned int)attrs[1] < attrdatastart)
attrdatastart = attrs[1];
break;
case REPOKEY_TYPE_DIRSTRARRAY:
for (v = attrs[1]; data->attriddata[v] ; v += 2)
if ((unsigned int)data->attriddata[v + 1] < attrdatastart)
attrdatastart = data->attriddata[v + 1];
/* FALLTHROUGH */
case REPOKEY_TYPE_IDARRAY:
case REPOKEY_TYPE_DIRNUMNUMARRAY:
if ((unsigned int)attrs[1] < attriddatastart)
attriddatastart = attrs[1];
break;
case REPOKEY_TYPE_FIXARRAY:
case REPOKEY_TYPE_FLEXARRAY:
return;
default:
break;
}
}
}
#if 0
printf("compact_attrdata %d %d\n", entry, nentry);
printf("attrdatastart: %d\n", attrdatastart);
printf("attriddatastart: %d\n", attriddatastart);
#endif
if (attrdatastart < 1024 * 1024 * 4 && attriddatastart < 1024 * 1024)
return;
for (i = entry; i < nentry; i++)
{
Id v, *attrs = data->attrs[i];
if (!attrs)
continue;
for (; *attrs; attrs += 2)
{
switch (data->keys[*attrs].type)
{
case REPOKEY_TYPE_STR:
case REPOKEY_TYPE_BINARY:
case_CHKSUM_TYPES:
attrs[1] -= attrdatastart;
break;
case REPOKEY_TYPE_DIRSTRARRAY:
for (v = attrs[1]; data->attriddata[v] ; v += 2)
data->attriddata[v + 1] -= attrdatastart;
/* FALLTHROUGH */
case REPOKEY_TYPE_IDARRAY:
case REPOKEY_TYPE_DIRNUMNUMARRAY:
attrs[1] -= attriddatastart;
break;
default:
break;
}
}
}
if (attrdatastart)
{
data->attrdatalen -= attrdatastart;
memmove(data->attrdata, data->attrdata + attrdatastart, data->attrdatalen);
data->attrdata = solv_extend_resize(data->attrdata, data->attrdatalen, 1, REPODATA_ATTRDATA_BLOCK);
}
if (attriddatastart)
{
data->attriddatalen -= attriddatastart;
memmove(data->attriddata, data->attriddata + attriddatastart, data->attriddatalen * sizeof(Id));
data->attriddata = solv_extend_resize(data->attriddata, data->attriddatalen, sizeof(Id), REPODATA_ATTRIDDATA_BLOCK);
}
}
/* internalalize some key into incore/vincore data */
static void
repodata_serialize_key(Repodata *data, struct extdata *newincore,
struct extdata *newvincore,
Id *schema,
Repokey *key, Id val)
{
Id *ida;
struct extdata *xd;
unsigned int oldvincorelen = 0;
Id schemaid, *sp;
xd = newincore;
if (key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
xd = newvincore;
oldvincorelen = xd->len;
}
switch (key->type)
{
case REPOKEY_TYPE_VOID:
case REPOKEY_TYPE_CONSTANT:
case REPOKEY_TYPE_CONSTANTID:
case REPOKEY_TYPE_DELETED:
break;
case REPOKEY_TYPE_STR:
data_addblob(xd, data->attrdata + val, strlen((char *)(data->attrdata + val)) + 1);
break;
case REPOKEY_TYPE_MD5:
data_addblob(xd, data->attrdata + val, SIZEOF_MD5);
break;
case REPOKEY_TYPE_SHA1:
data_addblob(xd, data->attrdata + val, SIZEOF_SHA1);
break;
case REPOKEY_TYPE_SHA224:
data_addblob(xd, data->attrdata + val, SIZEOF_SHA224);
break;
case REPOKEY_TYPE_SHA256:
data_addblob(xd, data->attrdata + val, SIZEOF_SHA256);
break;
case REPOKEY_TYPE_SHA384:
data_addblob(xd, data->attrdata + val, SIZEOF_SHA384);
break;
case REPOKEY_TYPE_SHA512:
data_addblob(xd, data->attrdata + val, SIZEOF_SHA512);
break;
case REPOKEY_TYPE_NUM:
if (val & 0x80000000)
{
data_addid64(xd, data->attrnum64data[val ^ 0x80000000]);
break;
}
/* FALLTHROUGH */
case REPOKEY_TYPE_ID:
case REPOKEY_TYPE_DIR:
data_addid(xd, val);
break;
case REPOKEY_TYPE_BINARY:
{
Id len;
unsigned char *dp = data_read_id(data->attrdata + val, &len);
dp += (unsigned int)len;
data_addblob(xd, data->attrdata + val, dp - (data->attrdata + val));
}
break;
case REPOKEY_TYPE_IDARRAY:
for (ida = data->attriddata + val; *ida; ida++)
data_addideof(xd, ida[0], ida[1] ? 0 : 1);
break;
case REPOKEY_TYPE_DIRNUMNUMARRAY:
for (ida = data->attriddata + val; *ida; ida += 3)
{
data_addid(xd, ida[0]);
data_addid(xd, ida[1]);
data_addideof(xd, ida[2], ida[3] ? 0 : 1);
}
break;
case REPOKEY_TYPE_DIRSTRARRAY:
for (ida = data->attriddata + val; *ida; ida += 2)
{
data_addideof(xd, ida[0], ida[2] ? 0 : 1);
data_addblob(xd, data->attrdata + ida[1], strlen((char *)(data->attrdata + ida[1])) + 1);
}
break;
case REPOKEY_TYPE_FIXARRAY:
{
int num = 0;
schemaid = 0;
for (ida = data->attriddata + val; *ida; ida++)
{
Id *kp;
sp = schema;
kp = data->xattrs[-*ida];
if (!kp)
continue; /* ignore empty elements */
num++;
for (; *kp; kp += 2)
*sp++ = *kp;
*sp = 0;
if (!schemaid)
schemaid = repodata_schema2id(data, schema, 1);
else if (schemaid != repodata_schema2id(data, schema, 0))
{
pool_debug(data->repo->pool, SOLV_ERROR, "repodata_serialize_key: fixarray substructs with different schemas\n");
num = 0;
break;
}
}
data_addid(xd, num);
if (!num)
break;
data_addid(xd, schemaid);
for (ida = data->attriddata + val; *ida; ida++)
{
Id *kp = data->xattrs[-*ida];
if (!kp)
continue;
for (; *kp; kp += 2)
repodata_serialize_key(data, newincore, newvincore, schema, data->keys + *kp, kp[1]);
}
break;
}
case REPOKEY_TYPE_FLEXARRAY:
{
int num = 0;
for (ida = data->attriddata + val; *ida; ida++)
num++;
data_addid(xd, num);
for (ida = data->attriddata + val; *ida; ida++)
{
Id *kp = data->xattrs[-*ida];
if (!kp)
{
data_addid(xd, 0); /* XXX */
continue;
}
sp = schema;
for (;*kp; kp += 2)
*sp++ = *kp;
*sp = 0;
schemaid = repodata_schema2id(data, schema, 1);
data_addid(xd, schemaid);
kp = data->xattrs[-*ida];
for (;*kp; kp += 2)
repodata_serialize_key(data, newincore, newvincore, schema, data->keys + *kp, kp[1]);
}
break;
}
default:
pool_debug(data->repo->pool, SOLV_FATAL, "repodata_serialize_key: don't know how to handle type %d\n", key->type);
exit(1);
}
if (key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
/* put offset/len in incore */
data_addid(newincore, data->lastverticaloffset + oldvincorelen);
oldvincorelen = xd->len - oldvincorelen;
data_addid(newincore, oldvincorelen);
}
}
/* create a circular linked list of all keys that share
* the same keyname */
static Id *
calculate_keylink(Repodata *data)
{
int i, j;
Id *link;
Id maxkeyname = 0, *keytable = 0;
link = solv_calloc(data->nkeys, sizeof(Id));
if (data->nkeys <= 2)
return link;
for (i = 1; i < data->nkeys; i++)
{
Id n = data->keys[i].name;
if (n >= maxkeyname)
{
keytable = solv_realloc2(keytable, n + 128, sizeof(Id));
memset(keytable + maxkeyname, 0, (n + 128 - maxkeyname) * sizeof(Id));
maxkeyname = n + 128;
}
j = keytable[n];
if (j)
link[i] = link[j];
else
j = i;
link[j] = i;
keytable[n] = i;
}
/* remove links that just point to themselfs */
for (i = 1; i < data->nkeys; i++)
if (link[i] == i)
link[i] = 0;
solv_free(keytable);
return link;
}
void
repodata_internalize(Repodata *data)
{
Repokey *key, solvkey;
Id entry, nentry;
Id schemaid, keyid, *schema, *sp, oldschemaid, *keyp, *seen;
Offset *oldincoreoffs = 0;
int schemaidx;
unsigned char *dp, *ndp;
int neednewschema;
struct extdata newincore;
struct extdata newvincore;
Id solvkeyid;
Id *keylink;
int haveoldkl;
if (!data->attrs && !data->xattrs)
return;
#if 0
printf("repodata_internalize %d\n", data->repodataid);
printf(" attr data: %d K\n", data->attrdatalen / 1024);
printf(" attrid data: %d K\n", data->attriddatalen / (1024 / 4));
#endif
newvincore.buf = data->vincore;
newvincore.len = data->vincorelen;
/* find the solvables key, create if needed */
memset(&solvkey, 0, sizeof(solvkey));
solvkey.name = REPOSITORY_SOLVABLES;
solvkey.type = REPOKEY_TYPE_FLEXARRAY;
solvkey.size = 0;
solvkey.storage = KEY_STORAGE_INCORE;
solvkeyid = repodata_key2id(data, &solvkey, data->end != data->start ? 1 : 0);
schema = solv_malloc2(data->nkeys, sizeof(Id));
seen = solv_malloc2(data->nkeys, sizeof(Id));
/* Merge the data already existing (in data->schemata, ->incoredata and
friends) with the new attributes in data->attrs[]. */
nentry = data->end - data->start;
memset(&newincore, 0, sizeof(newincore));
data_addid(&newincore, 0); /* start data at offset 1 */
data->mainschema = 0;
data->mainschemaoffsets = solv_free(data->mainschemaoffsets);
keylink = calculate_keylink(data);
/* join entry data */
/* we start with the meta data, entry -1 */
for (entry = -1; entry < nentry; entry++)
{
oldschemaid = 0;
dp = data->incoredata;
if (dp)
{
dp += entry >= 0 ? data->incoreoffset[entry] : 1;
dp = data_read_id(dp, &oldschemaid);
}
memset(seen, 0, data->nkeys * sizeof(Id));
#if 0
fprintf(stderr, "oldschemaid %d\n", oldschemaid);
fprintf(stderr, "schemata %d\n", data->schemata[oldschemaid]);
fprintf(stderr, "schemadata %p\n", data->schemadata);
#endif
/* seen: -1: old data, 0: skipped, >0: id + 1 */
neednewschema = 0;
sp = schema;
haveoldkl = 0;
for (keyp = data->schemadata + data->schemata[oldschemaid]; *keyp; keyp++)
{
if (seen[*keyp])
{
/* oops, should not happen */
neednewschema = 1;
continue;
}
seen[*keyp] = -1; /* use old marker */
*sp++ = *keyp;
if (keylink[*keyp])
haveoldkl = 1; /* potential keylink conflict */
}
/* strip solvables key */
if (entry < 0 && solvkeyid && seen[solvkeyid])
{
*sp = 0;
for (sp = keyp = schema; *sp; sp++)
if (*sp != solvkeyid)
*keyp++ = *sp;
sp = keyp;
seen[solvkeyid] = 0;
neednewschema = 1;
}
/* add new entries */
if (entry >= 0)
keyp = data->attrs ? data->attrs[entry] : 0;
else
keyp = data->xattrs ? data->xattrs[1] : 0;
if (keyp)
for (; *keyp; keyp += 2)
{
if (!seen[*keyp])
{
neednewschema = 1;
*sp++ = *keyp;
if (haveoldkl && keylink[*keyp]) /* this should be pretty rare */
{
Id kl;
for (kl = keylink[*keyp]; kl != *keyp; kl = keylink[kl])
if (seen[kl] == -1)
{
/* replacing old key kl, remove from schema and seen */
Id *osp;
for (osp = schema; osp < sp; osp++)
if (*osp == kl)
{
memmove(osp, osp + 1, (sp - osp) * sizeof(Id));
sp--;
seen[kl] = 0;
break;
}
}
}
}
seen[*keyp] = keyp[1] + 1;
}
/* add solvables key if needed */
if (entry < 0 && data->end != data->start)
{
*sp++ = solvkeyid; /* always last in schema */
neednewschema = 1;
}
/* commit schema */
*sp = 0;
if (neednewschema)
/* Ideally we'd like to sort the new schema here, to ensure
schema equality independend of the ordering. */
schemaid = repodata_schema2id(data, schema, 1);
else
schemaid = oldschemaid;
if (entry < 0)
{
data->mainschemaoffsets = solv_calloc(sp - schema, sizeof(Id));
data->mainschema = schemaid;
}
/* find offsets in old incore data */
if (oldschemaid)
{
Id *lastneeded = 0;
for (sp = data->schemadata + data->schemata[oldschemaid]; *sp; sp++)
if (seen[*sp] == -1)
lastneeded = sp + 1;
if (lastneeded)
{
if (!oldincoreoffs)
oldincoreoffs = solv_malloc2(data->nkeys, 2 * sizeof(Offset));
for (sp = data->schemadata + data->schemata[oldschemaid]; sp != lastneeded; sp++)
{
/* Skip the data associated with this old key. */
key = data->keys + *sp;
ndp = dp;
if (key->storage == KEY_STORAGE_VERTICAL_OFFSET)
{
ndp = data_skip(ndp, REPOKEY_TYPE_ID);
ndp = data_skip(ndp, REPOKEY_TYPE_ID);
}
else if (key->storage == KEY_STORAGE_INCORE)
ndp = data_skip_key(data, ndp, key);
oldincoreoffs[*sp * 2] = dp - data->incoredata;
oldincoreoffs[*sp * 2 + 1] = ndp - dp;
dp = ndp;
}
}
}
/* just copy over the complete old entry (including the schemaid) if there was no new data */
if (entry >= 0 && !neednewschema && oldschemaid && (!data->attrs || !data->attrs[entry]) && dp)
{
ndp = data->incoredata + data->incoreoffset[entry];
data->incoreoffset[entry] = newincore.len;
data_addblob(&newincore, ndp, dp - ndp);
goto entrydone;
}
/* Now create data blob. We walk through the (possibly new) schema
and either copy over old data, or insert the new. */
if (entry >= 0)
data->incoreoffset[entry] = newincore.len;
data_addid(&newincore, schemaid);
/* we don't use a pointer to the schemadata here as repodata_serialize_key
* may call repodata_schema2id() which might realloc our schemadata */
for (schemaidx = data->schemata[schemaid]; (keyid = data->schemadata[schemaidx]) != 0; schemaidx++)
{
if (entry < 0)
{
data->mainschemaoffsets[schemaidx - data->schemata[schemaid]] = newincore.len;
if (keyid == solvkeyid)
{
/* add flexarray entry count */
data_addid(&newincore, data->end - data->start);
break; /* always the last entry */
}
}
if (seen[keyid] == -1)
{
if (oldincoreoffs[keyid * 2 + 1])
data_addblob(&newincore, data->incoredata + oldincoreoffs[keyid * 2], oldincoreoffs[keyid * 2 + 1]);
}
else if (seen[keyid])
repodata_serialize_key(data, &newincore, &newvincore, schema, data->keys + keyid, seen[keyid] - 1);
}
entrydone:
/* free memory */
if (entry >= 0 && data->attrs)
{
if (data->attrs[entry])
data->attrs[entry] = solv_free(data->attrs[entry]);
if (entry && entry % 4096 == 0 && data->nxattrs <= 2 && entry + 64 < nentry)
{
compact_attrdata(data, entry + 1, nentry); /* try to free some memory */
#if 0
printf(" attr data: %d K\n", data->attrdatalen / 1024);
printf(" attrid data: %d K\n", data->attriddatalen / (1024 / 4));
printf(" incore data: %d K\n", newincore.len / 1024);
printf(" sum: %d K\n", (newincore.len + data->attrdatalen + data->attriddatalen * 4) / 1024);
/* malloc_stats(); */
#endif
}
}
}
/* free all xattrs */
for (entry = 0; entry < data->nxattrs; entry++)
if (data->xattrs[entry])
solv_free(data->xattrs[entry]);
data->xattrs = solv_free(data->xattrs);
data->nxattrs = 0;
data->lasthandle = 0;
data->lastkey = 0;
data->lastdatalen = 0;
solv_free(schema);
solv_free(seen);
solv_free(keylink);
solv_free(oldincoreoffs);
repodata_free_schemahash(data);
solv_free(data->incoredata);
data->incoredata = newincore.buf;
data->incoredatalen = newincore.len;
data->incoredatafree = 0;
data->vincore = newvincore.buf;
data->vincorelen = newvincore.len;
data->attrs = solv_free(data->attrs);
data->attrdata = solv_free(data->attrdata);
data->attriddata = solv_free(data->attriddata);
data->attrnum64data = solv_free(data->attrnum64data);
data->attrdatalen = 0;
data->attriddatalen = 0;
data->attrnum64datalen = 0;
#if 0
printf("repodata_internalize %d done\n", data->repodataid);
printf(" incore data: %d K\n", data->incoredatalen / 1024);
#endif
}
void
repodata_disable_paging(Repodata *data)
{
if (maybe_load_repodata(data, 0))
{
repopagestore_disable_paging(&data->store);
data->storestate++;
}
}
/* call the pool's loadcallback to load a stub repodata */
static void
repodata_stub_loader(Repodata *data)
{
Repo *repo = data->repo;
Pool *pool = repo->pool;
int r, i;
struct s_Pool_tmpspace oldtmpspace;
Datapos oldpos;
if (!pool->loadcallback)
{
data->state = REPODATA_ERROR;
return;
}
data->state = REPODATA_LOADING;
/* save tmp space and pos */
oldtmpspace = pool->tmpspace;
memset(&pool->tmpspace, 0, sizeof(pool->tmpspace));
oldpos = pool->pos;
r = pool->loadcallback(pool, data, pool->loadcallbackdata);
/* restore tmp space and pos */
for (i = 0; i < POOL_TMPSPACEBUF; i++)
solv_free(pool->tmpspace.buf[i]);
pool->tmpspace = oldtmpspace;
if (r && oldpos.repo == repo && oldpos.repodataid == data->repodataid)
memset(&oldpos, 0, sizeof(oldpos));
pool->pos = oldpos;
data->state = r ? REPODATA_AVAILABLE : REPODATA_ERROR;
}
static inline void
repodata_add_stubkey(Repodata *data, Id keyname, Id keytype)
{
Repokey xkey;
xkey.name = keyname;
xkey.type = keytype;
xkey.storage = KEY_STORAGE_INCORE;
xkey.size = 0;
repodata_key2id(data, &xkey, 1);
}
static Repodata *
repodata_add_stub(Repodata **datap)
{
Repodata *data = *datap;
Repo *repo = data->repo;
Id repodataid = data - repo->repodata;
Repodata *sdata = repo_add_repodata(repo, 0);
data = repo->repodata + repodataid;
if (data->end > data->start)
repodata_extend_block(sdata, data->start, data->end - data->start);
sdata->state = REPODATA_STUB;
sdata->loadcallback = repodata_stub_loader;
*datap = data;
return sdata;
}
Repodata *
repodata_create_stubs(Repodata *data)
{
Repo *repo = data->repo;
Pool *pool = repo->pool;
Repodata *sdata;
int *stubdataids;
Dataiterator di;
Id xkeyname = 0;
int i, cnt = 0;
dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_EXTERNAL, 0, 0);
while (dataiterator_step(&di))
if (di.data == data)
cnt++;
dataiterator_free(&di);
if (!cnt)
return data;
stubdataids = solv_calloc(cnt, sizeof(*stubdataids));
for (i = 0; i < cnt; i++)
{
sdata = repodata_add_stub(&data);
stubdataids[i] = sdata - repo->repodata;
}
i = 0;
dataiterator_init(&di, pool, repo, SOLVID_META, REPOSITORY_EXTERNAL, 0, 0);
sdata = 0;
while (dataiterator_step(&di))
{
if (di.data != data)
continue;
if (di.key->name == REPOSITORY_EXTERNAL && !di.nparents)
{
dataiterator_entersub(&di);
sdata = repo->repodata + stubdataids[i++];
xkeyname = 0;
continue;
}
repodata_set_kv(sdata, SOLVID_META, di.key->name, di.key->type, &di.kv);
if (di.key->name == REPOSITORY_KEYS && di.key->type == REPOKEY_TYPE_IDARRAY)
{
if (!xkeyname)
{
if (!di.kv.eof)
xkeyname = di.kv.id;
}
else
{
repodata_add_stubkey(sdata, xkeyname, di.kv.id);
if (xkeyname == SOLVABLE_FILELIST)
repodata_set_filelisttype(sdata, REPODATA_FILELIST_EXTENSION);
xkeyname = 0;
}
}
}
dataiterator_free(&di);
for (i = 0; i < cnt; i++)
repodata_internalize(repo->repodata + stubdataids[i]);
solv_free(stubdataids);
return data;
}
void
repodata_set_filelisttype(Repodata *data, int type)
{
data->filelisttype = type;
}
unsigned int
repodata_memused(Repodata *data)
{
return data->incoredatalen + data->vincorelen;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1357_0 |
crossvul-cpp_data_good_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) {
if (dbg_data_len < 20) {
eprintf ("Truncated NB10 entry, not enough data to parse\n");
return 0;
}
SCV_NB10_HEADER nb10_hdr = {{0}};
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);
res->file_name[0] = 0;
if (nb10_hdr.file_name) {
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/good_144_0 |
crossvul-cpp_data_good_181_0 | /* radare - Apache 2.0 - Copyright 2010-2015 - pancake and
Adam Pridgen <dso@rice.edu || adam.pridgen@thecoverofnight.com> */
#include <string.h>
#include <r_types.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
#include <r_anal_ex.h>
#include <r_cons.h>
#include "../../../shlr/java/code.h"
#include "../../../shlr/java/class.h"
#ifdef IFDBG
#define dprintf eprintf
#endif
#define DO_THE_DBG 0
#define IFDBG if(DO_THE_DBG)
#define IFINT if(0)
struct r_anal_java_access_t;
typedef struct r_anal_java_access_t {
char *method;
ut64 addr;
ut64 value;
ut64 op_type;
struct r_anal_java_access_t *next;
struct r_anal_java_access_t *previous;
} RAnalJavaAccess;
typedef struct r_anal_java_local_var_t {
char *name;
char *type;
RList *writes;
RList *reads;
RList *binops;
} RAnalJavaLocalVar;
typedef struct r_anal_ex_java_lin_sweep {
RList *cfg_node_addrs;
}RAnalJavaLinearSweep;
ut64 METHOD_START = 0;
// XXX - TODO add code in the java_op that is aware of when it is in a
// switch statement, like in the shlr/java/code.c so that this does not
// report bad blocks. currently is should be easy to ignore these blocks,
// in output for the pdj
//static int java_print_ssa_bb (RAnal *anal, char *addr);
static int java_reset_counter (RAnal *anal, ut64 addr);
static int java_new_method (ut64 addr);
static void java_update_anal_types (RAnal *anal, RBinJavaObj *bin_obj);
static void java_set_function_prototype (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method);
static int java_cmd_ext(RAnal *anal, const char* input);
static int analyze_from_code_buffer (RAnal *anal, RAnalFunction *fcn, ut64 addr, const ut8 *code_buf, ut64 code_length);
static int analyze_from_code_attr (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method, ut64 loadaddr);
static int analyze_method(RAnal *anal, RAnalFunction *fcn, RAnalState *state);
static int java_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len);
//static int java_bb(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut8 *buf, ut64 len, int reftype);
//static int java_fn(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut8 *buf, ut64 len, int reftype);
static int java_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr);
static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state);
static int java_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr);
static int handle_bb_cf_linear_sweep (RAnal *anal, RAnalState *state);
static int java_post_anal_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr);
static RBinJavaObj * get_java_bin_obj(RAnal *anal);
static RList * get_java_bin_obj_list(RAnal *anal);
static int java_analyze_fns( RAnal *anal, ut64 start, ut64 end, int reftype, int depth);
//static RAnalOp * java_op_from_buffer(RAnal *anal, RAnalState *state, ut64 addr);
//static RAnalBlock * java_bb_from_buffer(RAnal *anal, RAnalState *state, ut64 addr);
//static RAnalFunction * java_fn_from_buffer(RAnal *anal, RAnalState *state, ut64 addr);
static int check_addr_in_code (RBinJavaField *method, ut64 addr);
static int check_addr_less_end (RBinJavaField *method, ut64 addr);
static int check_addr_less_start (RBinJavaField *method, ut64 addr);
static int java_revisit_bb_anal_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr);
static RBinJavaObj * get_java_bin_obj(RAnal *anal) {
RBin *b = anal->binb.bin;
RBinPlugin *plugin = b->cur && b->cur->o ? b->cur->o->plugin : NULL;
ut8 is_java = (plugin && strcmp (plugin->name, "java") == 0) ? 1 : 0;
return is_java ? b->cur->o->bin_obj : NULL;
}
static RList * get_java_bin_obj_list(RAnal *anal) {
RBinJavaObj *bin_obj = (RBinJavaObj * )get_java_bin_obj(anal);
// See libr/bin/p/bin_java.c to see what is happening here. The original intention
// was to use a shared global db variable from shlr/java/class.c, but the
// BIN_OBJS_ADDRS variable kept getting corrupted on Mac, so I (deeso) switched the
// way the access to the db was taking place by using the bin_obj as a proxy back
// to the BIN_OBJS_ADDRS which is instantiated in libr/bin/p/bin_java.c
// not the easiest way to make sausage, but its getting made.
return r_bin_java_get_bin_obj_list_thru_obj (bin_obj);
}
static int check_addr_less_end (RBinJavaField *method, ut64 addr) {
ut64 end = r_bin_java_get_method_code_size (method);
return (addr < end);
}
static int check_addr_in_code (RBinJavaField *method, ut64 addr) {
return !check_addr_less_start (method, addr) && \
check_addr_less_end ( method, addr);
}
static int check_addr_less_start (RBinJavaField *method, ut64 addr) {
ut64 start = r_bin_java_get_method_code_offset (method);
return (addr < start);
}
static int java_new_method (ut64 method_start) {
METHOD_START = method_start;
// reset the current bytes consumed counter
r_java_new_method ();
return 0;
}
static ut64 java_get_method_start () {
return METHOD_START;
}
static int java_revisit_bb_anal_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr) {
RAnalBlock *current_head = state && state->current_bb_head ? state->current_bb_head : NULL;
if (current_head && state->current_bb &&
state->current_bb->type & R_ANAL_BB_TYPE_TAIL) {
r_anal_ex_update_bb_cfg_head_tail (current_head, current_head, state->current_bb);
// XXX should i do this instead -> r_anal_ex_perform_post_anal_bb_cb (anal, state, addr+offset);
state->done = 1;
}
return R_ANAL_RET_END;
}
static int java_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr) {
RAnalBlock *bb;
RAnalBlock *current_head;
if (!anal || !state || !state->current_bb || state->current_bb_head)
return 0;
bb = state->current_bb;
current_head = state->current_bb_head;
if (current_head && state->current_bb->type & R_ANAL_BB_TYPE_TAIL) {
r_anal_ex_update_bb_cfg_head_tail (current_head, current_head, state->current_bb);
}
// basic filter for handling the different type of operations
// depending on flags some may be called more than once
// if (bb->type2 & R_ANAL_EX_ILL_OP) handle_bb_ill_op (anal, state);
// if (bb->type2 & R_ANAL_EX_COND_OP) handle_bb_cond_op (anal, state);
// if (bb->type2 & R_ANAL_EX_UNK_OP) handle_bb_unknown_op (anal, state);
// if (bb->type2 & R_ANAL_EX_NULL_OP) handle_bb_null_op (anal, state);
// if (bb->type2 & R_ANAL_EX_NOP_OP) handle_bb_nop_op (anal, state);
// if (bb->type2 & R_ANAL_EX_REP_OP) handle_bb_rep_op (anal, state);
// if (bb->type2 & R_ANAL_EX_STORE_OP) handle_bb_store_op (anal, state);
// if (bb->type2 & R_ANAL_EX_LOAD_OP) handle_bb_load_op (anal, state
// if (bb->type2 & R_ANAL_EX_REG_OP) handle_bb_reg_op (anal, state);
// if (bb->type2 & R_ANAL_EX_OBJ_OP) handle_bb_obj_op (anal, state);
// if (bb->type2 & R_ANAL_EX_STACK_OP) handle_bb_stack_op (anal, state);
// if (bb->type2 & R_ANAL_EX_BIN_OP) handle_bb_bin_op (anal, state);
if (bb->type2 & R_ANAL_EX_CODE_OP) handle_bb_cf_recursive_descent (anal, state);
// if (bb->type2 & R_ANAL_EX_DATA_OP) handle_bb_data_op (anal, state);
return 0;
}
static int java_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr) {
RAnalBlock *bb = state->current_bb;
if (state->current_bb_head && state->current_bb->type & R_ANAL_BB_TYPE_TAIL) {
//r_anal_ex_update_bb_cfg_head_tail (state->current_bb_head, state->current_bb_head, state->current_bb);
}
// basic filter for handling the different type of operations
// depending on flags some may be called more than once
// if (bb->type2 & R_ANAL_EX_ILL_OP) handle_bb_ill_op (anal, state);
// if (bb->type2 & R_ANAL_EX_COND_OP) handle_bb_cond_op (anal, state);
// if (bb->type2 & R_ANAL_EX_UNK_OP) handle_bb_unknown_op (anal, state);
// if (bb->type2 & R_ANAL_EX_NULL_OP) handle_bb_null_op (anal, state);
// if (bb->type2 & R_ANAL_EX_NOP_OP) handle_bb_nop_op (anal, state);
// if (bb->type2 & R_ANAL_EX_REP_OP) handle_bb_rep_op (anal, state);
// if (bb->type2 & R_ANAL_EX_STORE_OP) handle_bb_store_op (anal, state);
// if (bb->type2 & R_ANAL_EX_LOAD_OP) handle_bb_load_op (anal, state
// if (bb->type2 & R_ANAL_EX_REG_OP) handle_bb_reg_op (anal, state);
// if (bb->type2 & R_ANAL_EX_OBJ_OP) handle_bb_obj_op (anal, state);
// if (bb->type2 & R_ANAL_EX_STACK_OP) handle_bb_stack_op (anal, state);
// if (bb->type2 & R_ANAL_EX_BIN_OP) handle_bb_bin_op (anal, state);
if (bb->type2 & R_ANAL_EX_CODE_OP) handle_bb_cf_linear_sweep (anal, state);
// if (bb->type2 & R_ANAL_EX_DATA_OP) handle_bb_data_op (anal, state);
return 0;
}
static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state) {
RAnalBlock *bb = state->current_bb;
ut64 addr = 0;
int result = 0;
if (!bb) {
eprintf ("Error: unable to handle basic block @ 0x%08"PFMT64x"\n", addr);
return R_ANAL_RET_ERROR;
} else if (state->max_depth <= state->current_depth) {
return R_ANAL_RET_ERROR;
}
state->current_depth++;
addr = bb->addr;
IFDBG eprintf ("Handling a control flow change @ 0x%04"PFMT64x".\n", addr);
ut64 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2);
// XXX - transition to type2 control flow condtions
switch (control_type) {
case R_ANAL_OP_TYPE_CALL:
IFDBG eprintf (" - Handling a call @ 0x%04"PFMT64x".\n", addr);
r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL);
result = R_ANAL_RET_ERROR;
break;
case R_ANAL_OP_TYPE_JMP:
{
RList * jmp_list;
IFDBG eprintf (" - Handling a jmp @ 0x%04"PFMT64x" to 0x%04"PFMT64x".\n", addr, bb->jump);
// visited some other time
if (!r_anal_state_search_bb (state, bb->jump)) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump );
if (jmp_list)
bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (bb->jumpbb)
bb->jump = bb->jumpbb->addr;
} else {
bb->jumpbb = r_anal_state_search_bb (state, bb->jump);
if (bb->jumpbb)
bb->jump = bb->jumpbb->addr;
}
if (state->done == 1) {
IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr);
}
result = R_ANAL_RET_END;
}
break;
case R_ANAL_OP_TYPE_CJMP:
{
RList *jmp_list;
ut8 encountered_stop = 0;
IFDBG eprintf (" - Handling a cjmp @ 0x%04"PFMT64x" jmp to 0x%04"PFMT64x" and fail to 0x%04"PFMT64x".\n", addr, bb->jump, bb->fail);
IFDBG eprintf (" - Handling jmp to 0x%04"PFMT64x".\n", bb->jump);
// visited some other time
if (!r_anal_state_search_bb (state, bb->jump)) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump );
if (jmp_list)
bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (bb->jumpbb) {
bb->jump = bb->jumpbb->addr;
}
} else {
bb->jumpbb = r_anal_state_search_bb (state, bb->jump);
bb->jump = bb->jumpbb->addr;
}
if (state->done == 1) {
IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr);
state->done = 0;
encountered_stop = 1;
}
if (!r_anal_state_search_bb (state, bb->fail)) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->fail );
if (jmp_list)
bb->failbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (bb->failbb) {
bb->fail = bb->failbb->addr;
}
} else {
bb->failbb = r_anal_state_search_bb (state, bb->fail);
if (bb->failbb) {
bb->fail = bb->failbb->addr;
}
}
IFDBG eprintf (" - Handling an cjmp @ 0x%04"PFMT64x" jmp to 0x%04"PFMT64x" and fail to 0x%04"PFMT64x".\n", addr, bb->jump, bb->fail);
IFDBG eprintf (" - Handling fail to 0x%04"PFMT64x".\n", bb->fail);
// r_anal_state_merge_bb_list (state, fail_list);
if (state->done == 1) {
IFDBG eprintf (" Looks like this fail (bb @ 0x%04"PFMT64x") found a return.\n", addr);
}
result = R_ANAL_RET_END;
if (encountered_stop) state->done = 1;
}
break;
case R_ANAL_OP_TYPE_SWITCH:
{
IFDBG eprintf (" - Handling an switch @ 0x%04"PFMT64x".\n", addr);
if (bb->switch_op) {
RAnalCaseOp *caseop;
RListIter *iter;
RList *jmp_list = NULL;
ut8 encountered_stop = 0;
r_list_foreach (bb->switch_op->cases, iter, caseop) {
if (caseop) {
if (r_anal_state_addr_is_valid (state, caseop->jump) ) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, caseop->jump );
if (jmp_list)
caseop->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (state->done == 1) {
IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr);
state->done = 0;
encountered_stop = 1;
}
}
}
}
r_list_free (jmp_list);
if (encountered_stop) state->done = 1;
}
result = R_ANAL_RET_END;
}
break;
case R_ANAL_OP_TYPE_TRAP:
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_IJMP:
case R_ANAL_OP_TYPE_RJMP:
case R_ANAL_OP_TYPE_IRJMP:
case R_ANAL_OP_TYPE_RET:
case R_ANAL_OP_TYPE_ILL:
IFDBG eprintf (" - Handling an ret @ 0x%04"PFMT64x".\n", addr);
state->done = 1;
result = R_ANAL_RET_END;
break;
default: break;
}
state->current_depth--;
return result;
}
static int java_post_anal_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr) {
RAnalJavaLinearSweep *nodes = state->user_state;
RList *jmp_list = NULL;
ut64 *paddr64;
state->done = 0;
if (!nodes || !nodes->cfg_node_addrs) {
state->done = 1;
return R_ANAL_RET_ERROR;
}
while (r_list_length (nodes->cfg_node_addrs) > 0) {
paddr64 = r_list_get_n (nodes->cfg_node_addrs, 0);
r_list_del_n (nodes->cfg_node_addrs, 0);
if (paddr64 && !r_anal_state_search_bb (state, *paddr64)) {
ut64 list_length = 0;
IFDBG eprintf (" - Visiting 0x%04"PFMT64x" for analysis.\n", *paddr64);
jmp_list = r_anal_ex_perform_analysis ( anal, state, *paddr64 );
list_length = r_list_length (jmp_list);
r_list_free (jmp_list);
if ( list_length > 0) {
IFDBG eprintf (" - Found %"PFMT64d" more basic blocks missed on the initial pass.\n", *paddr64);
}
}
}
return R_ANAL_RET_END;
}
static int handle_bb_cf_linear_sweep (RAnal *anal, RAnalState *state) {
ut64 * paddr64;
RAnalBlock *bb = state->current_bb;
RAnalJavaLinearSweep *nodes = state->user_state;
if (!nodes || !nodes->cfg_node_addrs) {
state->done = 1;
return R_ANAL_RET_ERROR;
}
ut64 addr = 0;
int result = 0;
if (!bb) {
eprintf ("Error: unable to handle basic block @ 0x%08"PFMT64x"\n", addr);
return R_ANAL_RET_ERROR;
} else if (state->max_depth <= state->current_depth) {
return R_ANAL_RET_ERROR;
}
state->current_depth++;
addr = bb->addr;
IFDBG eprintf ("Handling a control flow change @ 0x%04"PFMT64x".\n", addr);
ut32 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2);
// XXX - transition to type2 control flow condtions
switch (control_type) {
case R_ANAL_OP_TYPE_CALL:
IFDBG eprintf (" - Handling a call @ 0x%04"PFMT64x"\n", addr);
r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL);
result = R_ANAL_RET_ERROR;
break;
case R_ANAL_OP_TYPE_JMP:
paddr64 = malloc (sizeof(ut64));
*paddr64 = bb->jump;
IFDBG eprintf (" - Handling a jmp @ 0x%04"PFMT64x", adding for future visit\n", addr);
r_list_append (nodes->cfg_node_addrs, paddr64);
result = R_ANAL_RET_END;
break;
case R_ANAL_OP_TYPE_CJMP:
paddr64 = malloc (sizeof(ut64));
*paddr64 = bb->jump;
IFDBG eprintf (" - Handling a bb->jump @ 0x%04"PFMT64x", adding 0x%04"PFMT64x" for future visit\n", addr, *paddr64);
r_list_append (nodes->cfg_node_addrs, paddr64);
paddr64 = malloc (sizeof(ut64));
if (paddr64) {
*paddr64 = bb->fail;
IFDBG eprintf (" - Handling a bb->fail @ 0x%04"PFMT64x", adding 0x%04"PFMT64x" for future visit\n", addr, *paddr64);
r_list_append (nodes->cfg_node_addrs, paddr64);
}
result = R_ANAL_RET_END;
break;
case R_ANAL_OP_TYPE_SWITCH:
if (bb->switch_op) {
RAnalCaseOp *caseop;
RListIter *iter;
//RList *jmp_list = NULL;
IFDBG eprintf (" - Handling a switch_op @ 0x%04"PFMT64x":\n", addr);
r_list_foreach (bb->switch_op->cases, iter, caseop) {
ut64 * paddr64;
if (caseop) {
paddr64 = malloc (sizeof(ut64));
*paddr64 = caseop->jump;
IFDBG eprintf ("Adding 0x%04"PFMT64x" for future visit\n", *paddr64);
r_list_append (nodes->cfg_node_addrs, paddr64);
}
}
}
result = R_ANAL_RET_END;
break;
case R_ANAL_OP_TYPE_TRAP:
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_RJMP:
case R_ANAL_OP_TYPE_IJMP:
case R_ANAL_OP_TYPE_IRJMP:
case R_ANAL_OP_TYPE_RET:
IFDBG eprintf (" - Handling an ret @ 0x%04"PFMT64x".\n", addr);
state->done = 1;
result = R_ANAL_RET_END;
break;
default: break;
}
state->current_depth--;
return result;
}
//many flaws UAF
static int analyze_from_code_buffer(RAnal *anal, RAnalFunction *fcn, ut64 addr, const ut8 *code_buf, ut64 code_length) {
char gen_name[1025];
RListIter *bb_iter;
RAnalBlock *bb;
ut64 actual_size = 0;
RAnalState *state = NULL;
int result = R_ANAL_RET_ERROR;
RAnalJavaLinearSweep *nodes;
free (fcn->name);
free (fcn->dsc);
snprintf (gen_name, 1024, "sym.%08"PFMT64x"", addr);
fcn->name = strdup (gen_name);
fcn->dsc = strdup ("unknown");
r_anal_fcn_set_size (NULL, fcn, code_length);
fcn->type = R_ANAL_FCN_TYPE_FCN;
fcn->addr = addr;
state = r_anal_state_new (addr, (ut8*) code_buf, code_length);
nodes = R_NEW0 (RAnalJavaLinearSweep);
nodes->cfg_node_addrs = r_list_new ();
nodes->cfg_node_addrs->free = free;
state->user_state = nodes;
result = analyze_method (anal, fcn, state);
r_list_foreach (fcn->bbs, bb_iter, bb) {
actual_size += bb->size;
}
r_anal_fcn_set_size (NULL, fcn, state->bytes_consumed);
result = state->anal_ret_val;
r_list_free (nodes->cfg_node_addrs);
free (nodes);
//leak to avoid UAF is the easy solution otherwise a whole rewrite is needed
//r_anal_state_free (state);
if (r_anal_fcn_size (fcn) != code_length) {
return R_ANAL_RET_ERROR;
#if 0
eprintf ("WARNING Analysis of %s Incorrect: Code Length: 0x%"PFMT64x", Function size reported 0x%x\n", fcn->name, code_length, r_anal_fcn_size(fcn));
eprintf ("Deadcode detected, setting code length to: 0x%"PFMT64x"\n", code_length);
r_anal_fcn_set_size (fcn, code_length);
#endif
}
return result;
}
static int analyze_from_code_attr (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method, ut64 loadaddr) {
RBinJavaAttrInfo* code_attr = method ? r_bin_java_get_method_code_attribute(method) : NULL;
ut8 * code_buf = NULL;
int result = false;
ut64 code_length = 0;
ut64 code_addr = -1;
if (!code_attr) {
fcn->name = strdup ("sym.UNKNOWN");
fcn->dsc = strdup ("unknown");
r_anal_fcn_set_size (NULL, fcn, code_length);
fcn->type = R_ANAL_FCN_TYPE_FCN;
fcn->addr = 0;
return R_ANAL_RET_ERROR;
}
code_length = code_attr->info.code_attr.code_length;
code_addr = code_attr->info.code_attr.code_offset;
code_buf = calloc (1, code_length);
anal->iob.read_at (anal->iob.io, code_addr + loadaddr, code_buf, code_length);
result = analyze_from_code_buffer (anal, fcn, code_addr + loadaddr, code_buf, code_length);
free (code_buf);
char *name = strdup (method->name);
if (name) {
r_name_filter (name, 80);
free (fcn->name);
if (method->class_name) {
char *cname = strdup (method->class_name);
r_name_filter (cname, 50);
fcn->name = r_str_newf ("sym.%s.%s", cname, name);
free (cname);
} else {
fcn->name = r_str_newf ("sym.%s", name);
}
free (name);
}
free (fcn->dsc);
fcn->dsc = strdup (method->descriptor);
IFDBG eprintf ("Completed analysing code from attr, name: %s, desc: %s", fcn->name, fcn->dsc);
return result;
}
static int analyze_method(RAnal *anal, RAnalFunction *fcn, RAnalState *state) {
// deallocate niceties
r_list_free (fcn->bbs);
fcn->bbs = r_anal_bb_list_new ();
java_new_method (fcn->addr);
state->current_fcn = fcn;
// Not a resource leak. Basic blocks should be stored in the state->fcn
// TODO: ? RList *bbs =
r_anal_ex_perform_analysis (anal, state, fcn->addr);
return state->anal_ret_val;
}
static int java_analyze_fns_from_buffer( RAnal *anal, ut64 start, ut64 end, int reftype, int depth) {
int result = R_ANAL_RET_ERROR;
ut64 addr = start;
ut64 offset = 0;
ut64 buf_len = end - start;
ut8 analyze_all = 0,
*buffer = NULL;
if (end == UT64_MAX) {
//analyze_all = 1;
buf_len = anal->iob.desc_size (anal->iob.io->desc);
if (buf_len == UT64_MAX) buf_len = 1024;
end = start + buf_len;
}
buffer = malloc (buf_len);
if (!buffer) {
return R_ANAL_RET_ERROR;
}
anal->iob.read_at (anal->iob.io, addr, buffer, buf_len);
while (offset < buf_len) {
ut64 length = buf_len - offset;
RAnalFunction *fcn = r_anal_fcn_new ();
fcn->cc = r_str_const (r_anal_cc_default (anal));
result = analyze_from_code_buffer ( anal, fcn, addr, buffer+offset, length );
if (result == R_ANAL_RET_ERROR) {
eprintf ("Failed to parse java fn: %s @ 0x%04"PFMT64x"\n", fcn->name, fcn->addr);
// XXX - TO Stop or not to Stop ??
break;
}
//r_listrange_add (anal->fcnstore, fcn);
r_anal_fcn_tree_insert (&anal->fcn_tree, fcn);
r_list_append (anal->fcns, fcn);
offset += r_anal_fcn_size (fcn);
if (!analyze_all) break;
}
free (buffer);
return result;
}
static int java_analyze_fns( RAnal *anal, ut64 start, ut64 end, int reftype, int depth) {
//anal->iob.read_at (anal->iob.io, op.jump, bbuf, sizeof (bbuf));
RBinJavaObj *bin = NULL;// = get_java_bin_obj (anal);
RBinJavaField *method = NULL;
RListIter *methods_iter, *bin_obs_iter;
RList * bin_objs_list = get_java_bin_obj_list (anal);
ut8 analyze_all = 0;
//RAnalRef *ref = NULL;
int result = R_ANAL_RET_ERROR;
if (end == UT64_MAX) {
analyze_all = 1;
}
if (!bin_objs_list || r_list_empty (bin_objs_list)) {
r_list_free (bin_objs_list);
return java_analyze_fns_from_buffer (anal, start, end, reftype, depth);
}
r_list_foreach (bin_objs_list, bin_obs_iter, bin) {
// loop over all bin object that are loaded
java_update_anal_types (anal, bin);
RList *methods_list = (RList *) r_bin_java_get_methods_list (bin);
ut64 loadaddr = bin->loadaddr;
// loop over all methods in the binary object and analyse
// the functions
r_list_foreach (methods_list, methods_iter, method) {
if ((method && analyze_all) ||
(check_addr_less_start (method, end) ||
check_addr_in_code (method, end))) {
RAnalFunction *fcn = r_anal_fcn_new ();
fcn->cc = r_str_const (r_anal_cc_default (anal));
java_set_function_prototype (anal, fcn, method);
result = analyze_from_code_attr (anal, fcn, method, loadaddr);
if (result == R_ANAL_RET_ERROR) {
//eprintf ("Failed to parse java fn: %s @ 0x%04"PFMT64x"\n", fcn->name, fcn->addr);
return result;
// XXX - TO Stop or not to Stop ??
}
//r_listrange_add (anal->fcnstore, fcn);
r_anal_fcn_update_tinyrange_bbs (fcn);
r_anal_fcn_tree_insert (&anal->fcn_tree, fcn);
r_list_append (anal->fcns, fcn);
}
} // End of methods loop
}// end of bin_objs list loop
return result;
}
/*static int java_fn(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut8 *buf, ut64 len, int reftype) {
// XXX - this may clash with malloc:// uris because the file name is
// malloc:// **
RBinJavaObj *bin = (RBinJavaObj *) get_java_bin_obj (anal);
RBinJavaField *method = bin ? r_bin_java_get_method_code_attribute_with_addr (bin, addr) : NULL;
ut64 loadaddr = bin ? bin->loadaddr : 0;
IFDBG eprintf ("Analyzing java functions for %s\n", anal->iob.io->fd->name);
if (method) return analyze_from_code_attr (anal, fcn, method, loadaddr);
return analyze_from_code_buffer (anal, fcn, addr, buf, len);
}*/
static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
// handle a table switch condition
if (pos + 8 + 8 > len) {
return op->size;
}
const int min_val = (ut32)(UINT (data, pos + 4));
const int max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
//caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset);
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
//ut32 value = (ut32)(UINT (data, pos));
if (pos + 4 >= len) {
// switch is too big cant read further
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
static int java_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
/* get opcode size */
//ut8 op_byte = data[0];
ut8 op_byte = data[0];
int sz = JAVA_OPS[op_byte].size;
if (!op) {
return sz;
}
memset (op, '\0', sizeof (RAnalOp));
IFDBG {
//eprintf ("Extracting op from buffer (%d byte(s)) @ 0x%04x\n", len, addr);
//eprintf ("Parsing op: (0x%02x) %s.\n", op_byte, JAVA_OPS[op_byte].name);
}
op->addr = addr;
op->size = sz;
op->id = data[0];
op->type2 = JAVA_OPS[op_byte].op_type;
op->type = r_anal_ex_map_anal_ex_to_anal_op_type (op->type2);
// handle lookup and table switch offsets
if (op_byte == 0xaa || op_byte == 0xab) {
java_switch_op (anal, op, addr, data, len);
// IN_SWITCH_OP = 1;
}
/* TODO:
// not sure how to handle the states for IN_SWITCH_OP, SWITCH_OP_CASES,
// and NUM_CASES_SEEN, because these are dependent on whether or not we
// are in a switch, and given the non-reentrant state of opcode analysis
// this can't always be guaranteed. Below is the pseudo code for handling
// the easy parts though
if (IN_SWITCH_OP) {
NUM_CASES_SEEN++;
if (NUM_CASES_SEEN == SWITCH_OP_CASES) IN_SWITCH_OP=0;
op->addr = addr;
op->size = 4;
op->type2 = 0;
op->type = R_ANAL_OP_TYPE_CASE
op->eob = 0;
return op->sizes;
}
*/
op->eob = r_anal_ex_is_op_type_eop (op->type2);
IFDBG {
const char *ot_str = r_anal_optype_to_string (op->type);
eprintf ("op_type2: %s @ 0x%04"PFMT64x" 0x%08"PFMT64x" op_type: (0x%02"PFMT64x") %s.\n",
JAVA_OPS[op_byte].name, addr, (ut64)op->type2, (ut64)op->type, ot_str);
//eprintf ("op_eob: 0x%02x.\n", op->eob);
//eprintf ("op_byte @ 0: 0x%02x op_byte @ 0x%04x: 0x%02x.\n", data[0], addr, data[addr]);
}
if (len < 4) {
// incomplete analysis here
return 0;
}
if (op->type == R_ANAL_OP_TYPE_CJMP) {
op->jump = addr + (short)(USHORT (data, 1));
op->fail = addr + sz;
IFDBG eprintf ("%s jmpto 0x%04"PFMT64x" failto 0x%04"PFMT64x".\n",
JAVA_OPS[op_byte].name, op->jump, op->fail);
} else if (op->type == R_ANAL_OP_TYPE_JMP) {
op->jump = addr + (short)(USHORT (data, 1));
IFDBG eprintf ("%s jmpto 0x%04"PFMT64x".\n", JAVA_OPS[op_byte].name, op->jump);
} else if ( (op->type & R_ANAL_OP_TYPE_CALL) == R_ANAL_OP_TYPE_CALL ) {
op->jump = (int)(short)(USHORT (data, 1));
op->fail = addr + sz;
//IFDBG eprintf ("%s callto 0x%04x failto 0x%04x.\n", JAVA_OPS[op_byte].name, op->jump, op->fail);
}
//r_java_disasm(addr, data, len, output, outlen);
//IFDBG eprintf ("%s\n", output);
return op->size;
}
/*
static RAnalOp * java_op_from_buffer(RAnal *anal, RAnalState *state, ut64 addr) {
RAnalOp *op = r_anal_op_new ();
// get opcode size
if (!op) return 0;
memset (op, '\0', sizeof (RAnalOp));
java_op (anal, op, addr, state->buffer, state->len - (addr - state->start) );
return op;
}
*/
static void java_set_function_prototype (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method) {
RList *the_list = r_bin_java_extract_type_values (method->descriptor);
Sdb *D = anal->sdb_types;
Sdb *A = anal->sdb_args;
const char *type_fmt = "%08"PFMT64x".arg.%d.type",
*namek_fmt = "%08"PFMT64x".var.%d.name",
*namev_fmt = "%08"PFMT64x"local.%d";
char key_buf[1024], value_buf [1024];
RListIter *iter;
char *str;
if (the_list) {
ut8 start = 0, stop = 0;
int idx = 0;
r_list_foreach (the_list, iter, str) {
IFDBG eprintf ("Adding type: %s to known types.\n", str);
if (str && *str == '('){
start = 1;
continue;
}
if (str && start && *str != ')') {
// set type
// set arg type
snprintf (key_buf, sizeof(key_buf)-1, type_fmt, (ut64)fcn->addr, idx);
sdb_set (A, str, key_buf, 0);
sdb_set (D, str, "type", 0);
// set value
snprintf (key_buf, sizeof(key_buf)-1, namek_fmt, fcn->addr, idx);
snprintf (value_buf, sizeof(value_buf)-1, namev_fmt, fcn->addr, idx);
sdb_set (A, value_buf, key_buf, 0);
idx ++;
}
if (start && str && *str == ')') {
stop = 1;
continue;
}
if ((start & stop & 1) && str) {
sdb_set (A, str, "ret.type", 0);
sdb_set (D, str, "type", 0);
}
}
r_list_free (the_list);
}
}
static void java_update_anal_types (RAnal *anal, RBinJavaObj *bin_obj) {
Sdb *D = anal->sdb_types;
if (D && bin_obj) {
RListIter *iter;
char *str;
RList * the_list = r_bin_java_extract_all_bin_type_values (bin_obj);
if (the_list) {
r_list_foreach (the_list, iter, str) {
IFDBG eprintf ("Adding type: %s to known types.\n", str);
if (str) sdb_set (D, str, "type", 0);
}
}
r_list_free (the_list);
}
}
static int java_cmd_ext(RAnal *anal, const char* input) {
RBinJavaObj *obj = (RBinJavaObj *) get_java_bin_obj (anal);
if (!obj) {
eprintf ("Execute \"af\" to set the current bin, and this will bind the current bin\n");
return -1;
}
switch (*input) {
case 'c':
// reset bytes counter for case operations
r_java_new_method ();
break;
case 'u':
switch (*(input+1)) {
case 't': {java_update_anal_types (anal, obj); return true;}
default: break;
}
break;
case 's':
switch (*(input+1)) {
//case 'e': return java_resolve_cp_idx_b64 (anal, input+2);
default: break;
}
break;
default: eprintf("Command not supported"); break;
}
return 0;
}
static int java_reset_counter (RAnal *anal, ut64 start_addr ) {
IFDBG eprintf ("Setting the new METHOD_START to 0x%08"PFMT64x" was 0x%08"PFMT64x"\n", start_addr, METHOD_START);
METHOD_START = start_addr;
r_java_new_method ();
return true;
}
RAnalPlugin r_anal_plugin_java = {
.name = "java",
.desc = "Java bytecode analysis plugin",
.license = "Apache",
.arch = "java",
.bits = 32,
.custom_fn_anal = 1,
.reset_counter = java_reset_counter,
.analyze_fns = java_analyze_fns,
.post_anal_bb_cb = java_recursive_descent,
.revisit_bb_anal = java_revisit_bb_anal_recursive_descent,
.op = &java_op,
.cmd_ext = java_cmd_ext,
0
};
RAnalPlugin r_anal_plugin_java_ls = {
.name = "java_ls",
.desc = "Java bytecode analysis plugin with linear sweep",
.license = "Apache",
.arch = "java",
.bits = 32,
.custom_fn_anal = 1,
.analyze_fns = java_analyze_fns,
.post_anal_bb_cb = java_linear_sweep,
.post_anal = java_post_anal_linear_sweep,
.revisit_bb_anal = java_revisit_bb_anal_recursive_descent,
.op = &java_op,
.cmd_ext = java_cmd_ext,
0
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
//.data = &r_anal_plugin_java
.data = &r_anal_plugin_java_ls,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_181_0 |
crossvul-cpp_data_bad_2723_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;
int sysid_len;
sysid_len = SYSTEM_ID_LEN;
if (sysid_len > id_len)
sysid_len = id_len;
for (i = 1; i <= sysid_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/bad_2723_0 |
crossvul-cpp_data_good_3905_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Windowing Alternate Secondary Orders
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2011 Roman Barabanov <romanbarabanov@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 <winpr/crt.h>
#include <freerdp/log.h>
#include "window.h"
#define TAG FREERDP_TAG("core.window")
static void update_free_window_icon_info(ICON_INFO* iconInfo);
BOOL rail_read_unicode_string(wStream* s, RAIL_UNICODE_STRING* unicode_string)
{
UINT16 new_len;
BYTE* new_str;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, new_len); /* cbString (2 bytes) */
if (Stream_GetRemainingLength(s) < new_len)
return FALSE;
if (!new_len)
{
free(unicode_string->string);
unicode_string->string = NULL;
unicode_string->length = 0;
return TRUE;
}
new_str = (BYTE*)realloc(unicode_string->string, new_len);
if (!new_str)
{
free(unicode_string->string);
unicode_string->string = NULL;
return FALSE;
}
unicode_string->string = new_str;
unicode_string->length = new_len;
Stream_Read(s, unicode_string->string, unicode_string->length);
return TRUE;
}
BOOL utf8_string_to_rail_string(const char* string, RAIL_UNICODE_STRING* unicode_string)
{
WCHAR* buffer = NULL;
int length = 0;
free(unicode_string->string);
unicode_string->string = NULL;
unicode_string->length = 0;
if (!string || strlen(string) < 1)
return TRUE;
length = ConvertToUnicode(CP_UTF8, 0, string, -1, &buffer, 0);
if ((length < 0) || ((size_t)length * sizeof(WCHAR) > UINT16_MAX))
{
free(buffer);
return FALSE;
}
unicode_string->string = (BYTE*)buffer;
unicode_string->length = (UINT16)length * sizeof(WCHAR);
return TRUE;
}
/* See [MS-RDPERP] 2.2.1.2.3 Icon Info (TS_ICON_INFO) */
static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)
{
BYTE* newBitMask;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */
Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */
if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", iconInfo->bpp);
return FALSE;
}
Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */
Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */
/* cbColorTable is only present when bpp is 1, 4 or 8 */
switch (iconInfo->bpp)
{
case 1:
case 4:
case 8:
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */
break;
default:
iconInfo->cbColorTable = 0;
break;
}
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */
Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */
/* bitsMask */
newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);
if (!newBitMask)
{
free(iconInfo->bitsMask);
iconInfo->bitsMask = NULL;
return FALSE;
}
iconInfo->bitsMask = newBitMask;
if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask)
return FALSE;
Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);
/* colorTable */
if (iconInfo->colorTable == NULL)
{
if (iconInfo->cbColorTable)
{
iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);
if (!iconInfo->colorTable)
return FALSE;
}
}
else if (iconInfo->cbColorTable)
{
BYTE* new_tab;
new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);
if (!new_tab)
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
return FALSE;
}
iconInfo->colorTable = new_tab;
}
else
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
}
if (iconInfo->colorTable)
{
if (Stream_GetRemainingLength(s) < iconInfo->cbColorTable)
return FALSE;
Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);
}
/* bitsColor */
newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);
if (!newBitMask)
{
free(iconInfo->bitsColor);
iconInfo->bitsColor = NULL;
return FALSE;
}
iconInfo->bitsColor = newBitMask;
if (Stream_GetRemainingLength(s) < iconInfo->cbBitsColor)
return FALSE;
Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);
return TRUE;
}
static BOOL update_read_cached_icon_info(wStream* s, CACHED_ICON_INFO* cachedIconInfo)
{
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
Stream_Read_UINT16(s, cachedIconInfo->cacheEntry); /* cacheEntry (2 bytes) */
Stream_Read_UINT8(s, cachedIconInfo->cacheId); /* cacheId (1 byte) */
return TRUE;
}
static BOOL update_read_notify_icon_infotip(wStream* s, NOTIFY_ICON_INFOTIP* notifyIconInfoTip)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, notifyIconInfoTip->timeout); /* timeout (4 bytes) */
Stream_Read_UINT32(s, notifyIconInfoTip->flags); /* infoFlags (4 bytes) */
return rail_read_unicode_string(s, ¬ifyIconInfoTip->text) && /* infoTipText */
rail_read_unicode_string(s, ¬ifyIconInfoTip->title); /* title */
}
static BOOL update_read_window_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
WINDOW_STATE_ORDER* windowState)
{
UINT32 i;
size_t size;
RECTANGLE_16* newRect;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, windowState->ownerWindowId); /* ownerWindowId (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->style); /* style (4 bytes) */
Stream_Read_UINT32(s, windowState->extendedStyle); /* extendedStyle (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->showState); /* showState (1 byte) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE)
{
if (!rail_read_unicode_string(s, &windowState->titleInfo)) /* titleInfo */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_INT32(s, windowState->clientOffsetX); /* clientOffsetX (4 bytes) */
Stream_Read_INT32(s, windowState->clientOffsetY); /* clientOffsetY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->clientAreaWidth); /* clientAreaWidth (4 bytes) */
Stream_Read_UINT32(s, windowState->clientAreaHeight); /* clientAreaHeight (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->resizeMarginLeft);
Stream_Read_UINT32(s, windowState->resizeMarginRight);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->resizeMarginTop);
Stream_Read_UINT32(s, windowState->resizeMarginBottom);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->RPContent); /* RPContent (1 byte) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, windowState->rootParentHandle); /* rootParentHandle (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_INT32(s, windowState->windowOffsetX); /* windowOffsetX (4 bytes) */
Stream_Read_INT32(s, windowState->windowOffsetY); /* windowOffsetY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_INT32(s, windowState->windowClientDeltaX); /* windowClientDeltaX (4 bytes) */
Stream_Read_INT32(s, windowState->windowClientDeltaY); /* windowClientDeltaY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->windowWidth); /* windowWidth (4 bytes) */
Stream_Read_UINT32(s, windowState->windowHeight); /* windowHeight (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, windowState->numWindowRects); /* numWindowRects (2 bytes) */
if (windowState->numWindowRects == 0)
{
return TRUE;
}
size = sizeof(RECTANGLE_16) * windowState->numWindowRects;
newRect = (RECTANGLE_16*)realloc(windowState->windowRects, size);
if (!newRect)
{
free(windowState->windowRects);
windowState->windowRects = NULL;
return FALSE;
}
windowState->windowRects = newRect;
if (Stream_GetRemainingLength(s) < 8 * windowState->numWindowRects)
return FALSE;
/* windowRects */
for (i = 0; i < windowState->numWindowRects; i++)
{
Stream_Read_UINT16(s, windowState->windowRects[i].left); /* left (2 bytes) */
Stream_Read_UINT16(s, windowState->windowRects[i].top); /* top (2 bytes) */
Stream_Read_UINT16(s, windowState->windowRects[i].right); /* right (2 bytes) */
Stream_Read_UINT16(s, windowState->windowRects[i].bottom); /* bottom (2 bytes) */
}
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->visibleOffsetX); /* visibleOffsetX (4 bytes) */
Stream_Read_UINT32(s, windowState->visibleOffsetY); /* visibleOffsetY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, windowState->numVisibilityRects); /* numVisibilityRects (2 bytes) */
if (windowState->numVisibilityRects != 0)
{
size = sizeof(RECTANGLE_16) * windowState->numVisibilityRects;
newRect = (RECTANGLE_16*)realloc(windowState->visibilityRects, size);
if (!newRect)
{
free(windowState->visibilityRects);
windowState->visibilityRects = NULL;
return FALSE;
}
windowState->visibilityRects = newRect;
if (Stream_GetRemainingLength(s) < windowState->numVisibilityRects * 8)
return FALSE;
/* visibilityRects */
for (i = 0; i < windowState->numVisibilityRects; i++)
{
Stream_Read_UINT16(s, windowState->visibilityRects[i].left); /* left (2 bytes) */
Stream_Read_UINT16(s, windowState->visibilityRects[i].top); /* top (2 bytes) */
Stream_Read_UINT16(s, windowState->visibilityRects[i].right); /* right (2 bytes) */
Stream_Read_UINT16(s,
windowState->visibilityRects[i].bottom); /* bottom (2 bytes) */
}
}
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION)
{
if (!rail_read_unicode_string(s, &windowState->OverlayDescription))
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_OVERLAY_NULL)
{
/* no data to be read here */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->TaskbarButton);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->EnforceServerZOrder);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->AppBarState);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->AppBarEdge);
}
return TRUE;
}
static BOOL update_read_window_icon_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
WINDOW_ICON_ORDER* window_icon)
{
WINPR_UNUSED(orderInfo);
window_icon->iconInfo = (ICON_INFO*)calloc(1, sizeof(ICON_INFO));
if (!window_icon->iconInfo)
return FALSE;
return update_read_icon_info(s, window_icon->iconInfo); /* iconInfo (ICON_INFO) */
}
static BOOL update_read_window_cached_icon_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
WINDOW_CACHED_ICON_ORDER* window_cached_icon)
{
WINPR_UNUSED(orderInfo);
return update_read_cached_icon_info(
s, &window_cached_icon->cachedIcon); /* cachedIcon (CACHED_ICON_INFO) */
}
static void update_read_window_delete_order(wStream* s, WINDOW_ORDER_INFO* orderInfo)
{
/* window deletion event */
}
static BOOL window_order_supported(const rdpSettings* settings, UINT32 fieldFlags)
{
const UINT32 mask = (WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE | WINDOW_ORDER_FIELD_RP_CONTENT |
WINDOW_ORDER_FIELD_ROOT_PARENT);
BOOL dresult;
if (!settings)
return FALSE;
/* See [MS-RDPERP] 2.2.1.1.2 Window List Capability Set */
dresult = settings->AllowUnanouncedOrdersFromServer;
switch (settings->RemoteWndSupportLevel)
{
case WINDOW_LEVEL_SUPPORTED_EX:
return TRUE;
case WINDOW_LEVEL_SUPPORTED:
return ((fieldFlags & mask) == 0) || dresult;
case WINDOW_LEVEL_NOT_SUPPORTED:
return dresult;
default:
return dresult;
}
}
#define DUMP_APPEND(buffer, size, ...) \
do \
{ \
char* b = (buffer); \
size_t s = (size); \
size_t pos = strnlen(b, s); \
_snprintf(&b[pos], s - pos, __VA_ARGS__); \
} while (0)
static void dump_window_state_order(wLog* log, const char* msg, const WINDOW_ORDER_INFO* order,
const WINDOW_STATE_ORDER* state)
{
char buffer[3000] = { 0 };
const size_t bufferSize = sizeof(buffer) - 1;
_snprintf(buffer, bufferSize, "%s windowId=0x%" PRIu32 "", msg, order->windowId);
if (order->fieldFlags & WINDOW_ORDER_FIELD_OWNER)
DUMP_APPEND(buffer, bufferSize, " owner=0x%" PRIx32 "", state->ownerWindowId);
if (order->fieldFlags & WINDOW_ORDER_FIELD_STYLE)
{
DUMP_APPEND(buffer, bufferSize, " [ex]style=<0x%" PRIx32 ", 0x%" PRIx32 "", state->style,
state->extendedStyle);
if (state->style & WS_POPUP)
DUMP_APPEND(buffer, bufferSize, " popup");
if (state->style & WS_VISIBLE)
DUMP_APPEND(buffer, bufferSize, " visible");
if (state->style & WS_THICKFRAME)
DUMP_APPEND(buffer, bufferSize, " thickframe");
if (state->style & WS_BORDER)
DUMP_APPEND(buffer, bufferSize, " border");
if (state->style & WS_CAPTION)
DUMP_APPEND(buffer, bufferSize, " caption");
if (state->extendedStyle & WS_EX_NOACTIVATE)
DUMP_APPEND(buffer, bufferSize, " noactivate");
if (state->extendedStyle & WS_EX_TOOLWINDOW)
DUMP_APPEND(buffer, bufferSize, " toolWindow");
if (state->extendedStyle & WS_EX_TOPMOST)
DUMP_APPEND(buffer, bufferSize, " topMost");
DUMP_APPEND(buffer, bufferSize, ">");
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_SHOW)
{
const char* showStr;
switch (state->showState)
{
case 0:
showStr = "hidden";
break;
case 2:
showStr = "minimized";
break;
case 3:
showStr = "maximized";
break;
case 5:
showStr = "current";
break;
default:
showStr = "<unknown>";
break;
}
DUMP_APPEND(buffer, bufferSize, " show=%s", showStr);
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_TITLE)
DUMP_APPEND(buffer, bufferSize, " title");
if (order->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET)
DUMP_APPEND(buffer, bufferSize, " clientOffset=(%" PRId32 ",%" PRId32 ")",
state->clientOffsetX, state->clientOffsetY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE)
DUMP_APPEND(buffer, bufferSize, " clientAreaWidth=%" PRIu32 " clientAreaHeight=%" PRIu32 "",
state->clientAreaWidth, state->clientAreaHeight);
if (order->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X)
DUMP_APPEND(buffer, bufferSize,
" resizeMarginLeft=%" PRIu32 " resizeMarginRight=%" PRIu32 "",
state->resizeMarginLeft, state->resizeMarginRight);
if (order->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)
DUMP_APPEND(buffer, bufferSize,
" resizeMarginTop=%" PRIu32 " resizeMarginBottom=%" PRIu32 "",
state->resizeMarginTop, state->resizeMarginBottom);
if (order->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT)
DUMP_APPEND(buffer, bufferSize, " rpContent=0x%" PRIx32 "", state->RPContent);
if (order->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT)
DUMP_APPEND(buffer, bufferSize, " rootParent=0x%" PRIx32 "", state->rootParentHandle);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
DUMP_APPEND(buffer, bufferSize, " windowOffset=(%" PRId32 ",%" PRId32 ")",
state->windowOffsetX, state->windowOffsetY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA)
DUMP_APPEND(buffer, bufferSize, " windowClientDelta=(%" PRId32 ",%" PRId32 ")",
state->windowClientDeltaX, state->windowClientDeltaY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
DUMP_APPEND(buffer, bufferSize, " windowWidth=%" PRIu32 " windowHeight=%" PRIu32 "",
state->windowWidth, state->windowHeight);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS)
{
UINT32 i;
DUMP_APPEND(buffer, bufferSize, " windowRects=(");
for (i = 0; i < state->numWindowRects; i++)
{
DUMP_APPEND(buffer, bufferSize, "(%" PRIu16 ",%" PRIu16 ",%" PRIu16 ",%" PRIu16 ")",
state->windowRects[i].left, state->windowRects[i].top,
state->windowRects[i].right, state->windowRects[i].bottom);
}
DUMP_APPEND(buffer, bufferSize, ")");
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
DUMP_APPEND(buffer, bufferSize, " visibleOffset=(%" PRId32 ",%" PRId32 ")",
state->visibleOffsetX, state->visibleOffsetY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
{
UINT32 i;
DUMP_APPEND(buffer, bufferSize, " visibilityRects=(");
for (i = 0; i < state->numVisibilityRects; i++)
{
DUMP_APPEND(buffer, bufferSize, "(%" PRIu16 ",%" PRIu16 ",%" PRIu16 ",%" PRIu16 ")",
state->visibilityRects[i].left, state->visibilityRects[i].top,
state->visibilityRects[i].right, state->visibilityRects[i].bottom);
}
DUMP_APPEND(buffer, bufferSize, ")");
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION)
DUMP_APPEND(buffer, bufferSize, " overlayDescr");
if (order->fieldFlags & WINDOW_ORDER_FIELD_ICON_OVERLAY_NULL)
DUMP_APPEND(buffer, bufferSize, " iconOverlayNull");
if (order->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON)
DUMP_APPEND(buffer, bufferSize, " taskBarButton=0x%" PRIx8 "", state->TaskbarButton);
if (order->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER)
DUMP_APPEND(buffer, bufferSize, " enforceServerZOrder=0x%" PRIx8 "",
state->EnforceServerZOrder);
if (order->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE)
DUMP_APPEND(buffer, bufferSize, " appBarState=0x%" PRIx8 "", state->AppBarState);
if (order->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE)
{
const char* appBarEdgeStr;
switch (state->AppBarEdge)
{
case 0:
appBarEdgeStr = "left";
break;
case 1:
appBarEdgeStr = "top";
break;
case 2:
appBarEdgeStr = "right";
break;
case 3:
appBarEdgeStr = "bottom";
break;
default:
appBarEdgeStr = "<unknown>";
break;
}
DUMP_APPEND(buffer, bufferSize, " appBarEdge=%s", appBarEdgeStr);
}
WLog_Print(log, WLOG_DEBUG, buffer);
}
static BOOL update_recv_window_info_order(rdpUpdate* update, wStream* s,
WINDOW_ORDER_INFO* orderInfo)
{
rdpContext* context = update->context;
rdpWindowUpdate* window = update->window;
BOOL result = TRUE;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, orderInfo->windowId); /* windowId (4 bytes) */
if (orderInfo->fieldFlags & WINDOW_ORDER_ICON)
{
WINDOW_ICON_ORDER window_icon = { 0 };
result = update_read_window_icon_order(s, orderInfo, &window_icon);
if (result)
{
WLog_Print(update->log, WLOG_DEBUG, "WindowIcon windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->WindowIcon, result, context, orderInfo, &window_icon);
}
update_free_window_icon_info(window_icon.iconInfo);
free(window_icon.iconInfo);
}
else if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON)
{
WINDOW_CACHED_ICON_ORDER window_cached_icon = { 0 };
result = update_read_window_cached_icon_order(s, orderInfo, &window_cached_icon);
if (result)
{
WLog_Print(update->log, WLOG_DEBUG, "WindowCachedIcon windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->WindowCachedIcon, result, context, orderInfo, &window_cached_icon);
}
}
else if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_DELETED)
{
update_read_window_delete_order(s, orderInfo);
WLog_Print(update->log, WLOG_DEBUG, "WindowDelete windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->WindowDelete, result, context, orderInfo);
}
else
{
WINDOW_STATE_ORDER windowState = { 0 };
result = update_read_window_state_order(s, orderInfo, &windowState);
if (result)
{
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW)
{
dump_window_state_order(update->log, "WindowCreate", orderInfo, &windowState);
IFCALLRET(window->WindowCreate, result, context, orderInfo, &windowState);
}
else
{
dump_window_state_order(update->log, "WindowUpdate", orderInfo, &windowState);
IFCALLRET(window->WindowUpdate, result, context, orderInfo, &windowState);
}
update_free_window_state(&windowState);
}
}
return result;
}
static void update_notify_icon_state_order_free(NOTIFY_ICON_STATE_ORDER* notify)
{
free(notify->toolTip.string);
free(notify->infoTip.text.string);
free(notify->infoTip.title.string);
update_free_window_icon_info(¬ify->icon);
memset(notify, 0, sizeof(NOTIFY_ICON_STATE_ORDER));
}
static BOOL update_read_notification_icon_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
NOTIFY_ICON_STATE_ORDER* notify_icon_state)
{
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, notify_icon_state->version); /* version (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP)
{
if (!rail_read_unicode_string(s,
¬ify_icon_state->toolTip)) /* toolTip (UNICODE_STRING) */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP)
{
if (!update_read_notify_icon_infotip(
s, ¬ify_icon_state->infoTip)) /* infoTip (NOTIFY_ICON_INFOTIP) */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, notify_icon_state->state); /* state (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_ICON)
{
if (!update_read_icon_info(s, ¬ify_icon_state->icon)) /* icon (ICON_INFO) */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON)
{
if (!update_read_cached_icon_info(
s, ¬ify_icon_state->cachedIcon)) /* cachedIcon (CACHED_ICON_INFO) */
return FALSE;
}
return TRUE;
}
static void update_read_notification_icon_delete_order(wStream* s, WINDOW_ORDER_INFO* orderInfo)
{
/* notification icon deletion event */
}
static BOOL update_recv_notification_icon_info_order(rdpUpdate* update, wStream* s,
WINDOW_ORDER_INFO* orderInfo)
{
rdpContext* context = update->context;
rdpWindowUpdate* window = update->window;
BOOL result = TRUE;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, orderInfo->windowId); /* windowId (4 bytes) */
Stream_Read_UINT32(s, orderInfo->notifyIconId); /* notifyIconId (4 bytes) */
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_DELETED)
{
update_read_notification_icon_delete_order(s, orderInfo);
WLog_Print(update->log, WLOG_DEBUG, "NotifyIconDelete");
IFCALLRET(window->NotifyIconDelete, result, context, orderInfo);
}
else
{
NOTIFY_ICON_STATE_ORDER notify_icon_state = { 0 };
result = update_read_notification_icon_state_order(s, orderInfo, ¬ify_icon_state);
if (!result)
goto fail;
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW)
{
WLog_Print(update->log, WLOG_DEBUG, "NotifyIconCreate");
IFCALLRET(window->NotifyIconCreate, result, context, orderInfo, ¬ify_icon_state);
}
else
{
WLog_Print(update->log, WLOG_DEBUG, "NotifyIconUpdate");
IFCALLRET(window->NotifyIconUpdate, result, context, orderInfo, ¬ify_icon_state);
}
fail:
update_notify_icon_state_order_free(¬ify_icon_state);
}
return result;
}
static BOOL update_read_desktop_actively_monitored_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
MONITORED_DESKTOP_ORDER* monitored_desktop)
{
int i;
int size;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, monitored_desktop->activeWindowId); /* activeWindowId (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
{
UINT32* newid;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, monitored_desktop->numWindowIds); /* numWindowIds (1 byte) */
if (Stream_GetRemainingLength(s) < 4 * monitored_desktop->numWindowIds)
return FALSE;
if (monitored_desktop->numWindowIds > 0)
{
size = sizeof(UINT32) * monitored_desktop->numWindowIds;
newid = (UINT32*)realloc(monitored_desktop->windowIds, size);
if (!newid)
{
free(monitored_desktop->windowIds);
monitored_desktop->windowIds = NULL;
return FALSE;
}
monitored_desktop->windowIds = newid;
/* windowIds */
for (i = 0; i < (int)monitored_desktop->numWindowIds; i++)
{
Stream_Read_UINT32(s, monitored_desktop->windowIds[i]);
}
}
}
return TRUE;
}
static void update_read_desktop_non_monitored_order(wStream* s, WINDOW_ORDER_INFO* orderInfo)
{
/* non-monitored desktop notification event */
}
static void dump_monitored_desktop(wLog* log, const char* msg, const WINDOW_ORDER_INFO* orderInfo,
const MONITORED_DESKTOP_ORDER* monitored)
{
char buffer[1000] = { 0 };
const size_t bufferSize = sizeof(buffer) - 1;
DUMP_APPEND(buffer, bufferSize, "%s", msg);
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
DUMP_APPEND(buffer, bufferSize, " activeWindowId=0x%" PRIx32 "", monitored->activeWindowId);
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
{
UINT32 i;
DUMP_APPEND(buffer, bufferSize, " windows=(");
for (i = 0; i < monitored->numWindowIds; i++)
{
DUMP_APPEND(buffer, bufferSize, "0x%" PRIx32 ",", monitored->windowIds[i]);
}
DUMP_APPEND(buffer, bufferSize, ")");
}
WLog_Print(log, WLOG_DEBUG, buffer);
}
static BOOL update_recv_desktop_info_order(rdpUpdate* update, wStream* s,
WINDOW_ORDER_INFO* orderInfo)
{
rdpContext* context = update->context;
rdpWindowUpdate* window = update->window;
BOOL result = TRUE;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_NONE)
{
update_read_desktop_non_monitored_order(s, orderInfo);
WLog_Print(update->log, WLOG_DEBUG, "NonMonitoredDesktop, windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->NonMonitoredDesktop, result, context, orderInfo);
}
else
{
MONITORED_DESKTOP_ORDER monitored_desktop = { 0 };
result = update_read_desktop_actively_monitored_order(s, orderInfo, &monitored_desktop);
if (result)
{
dump_monitored_desktop(update->log, "ActivelyMonitoredDesktop", orderInfo,
&monitored_desktop);
IFCALLRET(window->MonitoredDesktop, result, context, orderInfo, &monitored_desktop);
}
free(monitored_desktop.windowIds);
}
return result;
}
void update_free_window_icon_info(ICON_INFO* iconInfo)
{
if (!iconInfo)
return;
free(iconInfo->bitsColor);
iconInfo->bitsColor = NULL;
free(iconInfo->bitsMask);
iconInfo->bitsMask = NULL;
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
}
BOOL update_recv_altsec_window_order(rdpUpdate* update, wStream* s)
{
BOOL rc = TRUE;
size_t remaining;
UINT16 orderSize;
WINDOW_ORDER_INFO orderInfo = { 0 };
remaining = Stream_GetRemainingLength(s);
if (remaining < 6)
{
WLog_Print(update->log, WLOG_ERROR, "Stream short");
return FALSE;
}
Stream_Read_UINT16(s, orderSize); /* orderSize (2 bytes) */
Stream_Read_UINT32(s, orderInfo.fieldFlags); /* FieldsPresentFlags (4 bytes) */
if (remaining + 1 < orderSize)
{
WLog_Print(update->log, WLOG_ERROR, "Stream short orderSize");
return FALSE;
}
if (!window_order_supported(update->context->settings, orderInfo.fieldFlags))
{
WLog_INFO(TAG, "Window order %08" PRIx32 " not supported!", orderInfo.fieldFlags);
return FALSE;
}
if (orderInfo.fieldFlags & WINDOW_ORDER_TYPE_WINDOW)
rc = update_recv_window_info_order(update, s, &orderInfo);
else if (orderInfo.fieldFlags & WINDOW_ORDER_TYPE_NOTIFY)
rc = update_recv_notification_icon_info_order(update, s, &orderInfo);
else if (orderInfo.fieldFlags & WINDOW_ORDER_TYPE_DESKTOP)
rc = update_recv_desktop_info_order(update, s, &orderInfo);
if (!rc)
WLog_Print(update->log, WLOG_ERROR, "windoworder flags %08" PRIx32 " failed",
orderInfo.fieldFlags);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3905_0 |
crossvul-cpp_data_bad_5249_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS GGGG IIIII %
% SS G I %
% SSS G GG I %
% SS G G I %
% SSSSS GGG IIIII %
% %
% %
% Read/Write Irix RGB Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Typedef declaractions.
*/
typedef struct _SGIInfo
{
unsigned short
magic;
unsigned char
storage,
bytes_per_pixel;
unsigned short
dimension,
columns,
rows,
depth;
size_t
minimum_value,
maximum_value,
sans;
char
name[80];
size_t
pixel_format;
unsigned char
filler[404];
} SGIInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteSGIImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S G I %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSGI() returns MagickTrue if the image format type, identified by the
% magick string, is SGI.
%
% The format of the IsSGI method is:
%
% MagickBooleanType IsSGI(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsSGI(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\001\332",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSGIImage() reads a SGI RGB image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadSGIImage method is:
%
% Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType SGIDecode(const size_t bytes_per_pixel,
ssize_t number_packets,unsigned char *packets,ssize_t number_pixels,
unsigned char *pixels)
{
register unsigned char
*p,
*q;
size_t
pixel;
ssize_t
count;
p=packets;
q=pixels;
if (bytes_per_pixel == 2)
{
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
*(q+1)=(*p++);
q+=8;
}
else
{
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(unsigned char) (pixel >> 8);
*(q+1)=(unsigned char) pixel;
q+=8;
}
}
}
return(MagickTrue);
}
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
q+=4;
}
else
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
for ( ; count != 0; count--)
{
*q=(unsigned char) pixel;
q+=4;
}
}
}
return(MagickTrue);
}
static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
(void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
(void) count;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSGIImage() adds properties for the SGI image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterSGIImage method is:
%
% size_t RegisterSGIImage(void)
%
*/
ModuleExport size_t RegisterSGIImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("SGI","SGI","Irix RGB image");
entry->decoder=(DecodeImageHandler *) ReadSGIImage;
entry->encoder=(EncodeImageHandler *) WriteSGIImage;
entry->magick=(IsImageFormatHandler *) IsSGI;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSGIImage() removes format registrations made by the
% SGI module from the list of supported formats.
%
% The format of the UnregisterSGIImage method is:
%
% UnregisterSGIImage(void)
%
*/
ModuleExport void UnregisterSGIImage(void)
{
(void) UnregisterMagickInfo("SGI");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSGIImage() writes an image in SGI RGB encoded image format.
%
% The format of the WriteSGIImage method is:
%
% MagickBooleanType WriteSGIImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t SGIEncode(unsigned char *pixels,size_t length,
unsigned char *packets)
{
short
runlength;
register unsigned char
*p,
*q;
unsigned char
*limit,
*mark;
p=pixels;
limit=p+length*4;
q=packets;
while (p < limit)
{
mark=p;
p+=8;
while ((p < limit) && ((*(p-8) != *(p-4)) || (*(p-4) != *p)))
p+=4;
p-=8;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) (0x80 | runlength);
for ( ; runlength > 0; runlength--)
{
*q++=(*mark);
mark+=4;
}
}
mark=p;
p+=4;
while ((p < limit) && (*p == *mark))
p+=4;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) runlength;
*q++=(*mark);
}
}
*q++='\0';
return((size_t) (q-packets));
}
static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
CompressionType
compression;
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
SGIInfo
iris_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
ssize_t
y,
z;
unsigned char
*pixels,
*packets;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SGI raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) ResetMagickMemory(&iris_info,0,sizeof(iris_info));
iris_info.magic=0x01DA;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (image->depth > 8)
compression=NoCompression;
if (compression == NoCompression)
iris_info.storage=(unsigned char) 0x00;
else
iris_info.storage=(unsigned char) 0x01;
iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1);
iris_info.dimension=3;
iris_info.columns=(unsigned short) image->columns;
iris_info.rows=(unsigned short) image->rows;
if (image->alpha_trait != UndefinedPixelTrait)
iris_info.depth=4;
else
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
iris_info.dimension=2;
iris_info.depth=1;
}
else
iris_info.depth=3;
}
iris_info.minimum_value=0;
iris_info.maximum_value=(size_t) (image->depth <= 8 ?
1UL*ScaleQuantumToChar(QuantumRange) :
1UL*ScaleQuantumToShort(QuantumRange));
/*
Write SGI header.
*/
(void) WriteBlobMSBShort(image,iris_info.magic);
(void) WriteBlobByte(image,iris_info.storage);
(void) WriteBlobByte(image,iris_info.bytes_per_pixel);
(void) WriteBlobMSBShort(image,iris_info.dimension);
(void) WriteBlobMSBShort(image,iris_info.columns);
(void) WriteBlobMSBShort(image,iris_info.rows);
(void) WriteBlobMSBShort(image,iris_info.depth);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans);
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name));
(void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format);
(void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler);
/*
Allocate SGI pixels.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*iris_info.bytes_per_pixel*number_pixels) !=
((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory((size_t) number_pixels,4*
iris_info.bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image pixels to uncompressed SGI pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (image->depth <= 8)
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
switch (compression)
{
case NoCompression:
{
/*
Write uncompressed SGI pixels.
*/
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (image->depth <= 8)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobByte(image,*q);
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobMSBShort(image,*q);
}
}
}
break;
}
default:
{
MemoryInfo
*packet_info;
size_t
length,
number_packets,
*runlength;
ssize_t
offset,
*offsets;
/*
Convert SGI uncompressed pixels.
*/
offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)*
image->rows,4*sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets != (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength != (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth);
number_packets=0;
q=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
length=SGIEncode(q+z,(size_t) iris_info.columns,packets+
number_packets);
number_packets+=length;
offsets[y+z*iris_info.rows]=offset;
runlength[y+z*iris_info.rows]=(size_t) length;
offset+=(ssize_t) length;
}
q+=(iris_info.columns*4);
}
/*
Write out line start and length tables and runlength-encoded pixels.
*/
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) offsets[i]);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) runlength[i]);
(void) WriteBlob(image,number_packets,packets);
/*
Relinquish resources.
*/
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5249_0 |
crossvul-cpp_data_good_1283_0 | /*
* This file includes functions to transform a concrete syntax tree (CST) to
* an abstract syntax tree (AST). The main function is Ta3AST_FromNode().
*
*/
#include "Python.h"
#include "Python-ast.h"
#include "node.h"
#include "ast.h"
#include "token.h"
#include "pythonrun.h"
#include <assert.h>
// VS 2010 doesn't have <stdbool.h>...
typedef int bool;
#define false 0
#define true 1
#ifndef _PyObject_FastCall
static PyObject *
_PyObject_FastCall(PyObject *func, PyObject *const *args, int nargs)
{
PyObject *t, *res;
int i;
t = PyTuple_New(nargs);
if (t == NULL) {
return NULL;
}
for (i = 0; i < nargs; i++) {
if (PyTuple_SetItem(t, i, args[i]) < 0) {
Py_DECREF(t);
return NULL;
}
}
res = PyObject_CallObject(func, t);
Py_DECREF(t);
return res;
}
#endif
#if PY_MINOR_VERSION < 6
#define _PyUnicode_EqualToASCIIString(a, b) (PyUnicode_CompareWithASCIIString((a), (b)) == 0)
static PyObject *
_PyBytes_DecodeEscape(const char *s,
Py_ssize_t len,
const char *errors,
Py_ssize_t unicode,
const char *recode_encoding,
const char **first_invalid_escape)
{
*first_invalid_escape = NULL;
return PyBytes_DecodeEscape(s, len, errors, unicode, recode_encoding);
}
PyObject *
_PyUnicode_DecodeUnicodeEscape(const char *s,
Py_ssize_t size,
const char *errors,
const char **first_invalid_escape)
{
*first_invalid_escape = NULL;
return PyUnicode_DecodeUnicodeEscape(s, size, errors);
}
#endif
static int validate_stmts(asdl_seq *);
static int validate_exprs(asdl_seq *, expr_context_ty, int);
static int validate_nonempty_seq(asdl_seq *, const char *, const char *);
static int validate_stmt(stmt_ty);
static int validate_expr(expr_ty, expr_context_ty);
void
_Ta3Parser_UpdateFlags(PyCompilerFlags *flags, int *iflags, int feature_version);
node *
Ta3Parser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
int start, int flags);
static int
validate_comprehension(asdl_seq *gens)
{
int i;
if (!asdl_seq_LEN(gens)) {
PyErr_SetString(PyExc_ValueError, "comprehension with no generators");
return 0;
}
for (i = 0; i < asdl_seq_LEN(gens); i++) {
comprehension_ty comp = asdl_seq_GET(gens, i);
if (!validate_expr(comp->target, Store) ||
!validate_expr(comp->iter, Load) ||
!validate_exprs(comp->ifs, Load, 0))
return 0;
}
return 1;
}
static int
validate_slice(slice_ty slice)
{
switch (slice->kind) {
case Slice_kind:
return (!slice->v.Slice.lower || validate_expr(slice->v.Slice.lower, Load)) &&
(!slice->v.Slice.upper || validate_expr(slice->v.Slice.upper, Load)) &&
(!slice->v.Slice.step || validate_expr(slice->v.Slice.step, Load));
case ExtSlice_kind: {
int i;
if (!validate_nonempty_seq(slice->v.ExtSlice.dims, "dims", "ExtSlice"))
return 0;
for (i = 0; i < asdl_seq_LEN(slice->v.ExtSlice.dims); i++)
if (!validate_slice(asdl_seq_GET(slice->v.ExtSlice.dims, i)))
return 0;
return 1;
}
case Index_kind:
return validate_expr(slice->v.Index.value, Load);
default:
PyErr_SetString(PyExc_SystemError, "unknown slice node");
return 0;
}
}
static int
validate_keywords(asdl_seq *keywords)
{
int i;
for (i = 0; i < asdl_seq_LEN(keywords); i++)
if (!validate_expr(((keyword_ty)asdl_seq_GET(keywords, i))->value, Load))
return 0;
return 1;
}
static int
validate_args(asdl_seq *args)
{
int i;
for (i = 0; i < asdl_seq_LEN(args); i++) {
arg_ty arg = asdl_seq_GET(args, i);
if (arg->annotation && !validate_expr(arg->annotation, Load))
return 0;
}
return 1;
}
static const char *
expr_context_name(expr_context_ty ctx)
{
switch (ctx) {
case Load:
return "Load";
case Store:
return "Store";
case Del:
return "Del";
case AugLoad:
return "AugLoad";
case AugStore:
return "AugStore";
case Param:
return "Param";
default:
abort();
}
}
static int
validate_arguments(arguments_ty args)
{
if (!validate_args(args->args))
return 0;
if (args->vararg && args->vararg->annotation
&& !validate_expr(args->vararg->annotation, Load)) {
return 0;
}
if (!validate_args(args->kwonlyargs))
return 0;
if (args->kwarg && args->kwarg->annotation
&& !validate_expr(args->kwarg->annotation, Load)) {
return 0;
}
if (asdl_seq_LEN(args->defaults) > asdl_seq_LEN(args->args)) {
PyErr_SetString(PyExc_ValueError, "more positional defaults than args on arguments");
return 0;
}
if (asdl_seq_LEN(args->kw_defaults) != asdl_seq_LEN(args->kwonlyargs)) {
PyErr_SetString(PyExc_ValueError, "length of kwonlyargs is not the same as "
"kw_defaults on arguments");
return 0;
}
return validate_exprs(args->defaults, Load, 0) && validate_exprs(args->kw_defaults, Load, 1);
}
static int
validate_constant(PyObject *value)
{
if (value == Py_None || value == Py_Ellipsis)
return 1;
if (PyLong_CheckExact(value)
|| PyFloat_CheckExact(value)
|| PyComplex_CheckExact(value)
|| PyBool_Check(value)
|| PyUnicode_CheckExact(value)
|| PyBytes_CheckExact(value))
return 1;
if (PyTuple_CheckExact(value) || PyFrozenSet_CheckExact(value)) {
PyObject *it;
it = PyObject_GetIter(value);
if (it == NULL)
return 0;
while (1) {
PyObject *item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred()) {
Py_DECREF(it);
return 0;
}
break;
}
if (!validate_constant(item)) {
Py_DECREF(it);
Py_DECREF(item);
return 0;
}
Py_DECREF(item);
}
Py_DECREF(it);
return 1;
}
return 0;
}
static int
validate_expr(expr_ty exp, expr_context_ty ctx)
{
int check_ctx = 1;
expr_context_ty actual_ctx;
/* First check expression context. */
switch (exp->kind) {
case Attribute_kind:
actual_ctx = exp->v.Attribute.ctx;
break;
case Subscript_kind:
actual_ctx = exp->v.Subscript.ctx;
break;
case Starred_kind:
actual_ctx = exp->v.Starred.ctx;
break;
case Name_kind:
actual_ctx = exp->v.Name.ctx;
break;
case List_kind:
actual_ctx = exp->v.List.ctx;
break;
case Tuple_kind:
actual_ctx = exp->v.Tuple.ctx;
break;
default:
if (ctx != Load) {
PyErr_Format(PyExc_ValueError, "expression which can't be "
"assigned to in %s context", expr_context_name(ctx));
return 0;
}
check_ctx = 0;
/* set actual_ctx to prevent gcc warning */
actual_ctx = 0;
}
if (check_ctx && actual_ctx != ctx) {
PyErr_Format(PyExc_ValueError, "expression must have %s context but has %s instead",
expr_context_name(ctx), expr_context_name(actual_ctx));
return 0;
}
/* Now validate expression. */
switch (exp->kind) {
case BoolOp_kind:
if (asdl_seq_LEN(exp->v.BoolOp.values) < 2) {
PyErr_SetString(PyExc_ValueError, "BoolOp with less than 2 values");
return 0;
}
return validate_exprs(exp->v.BoolOp.values, Load, 0);
case BinOp_kind:
return validate_expr(exp->v.BinOp.left, Load) &&
validate_expr(exp->v.BinOp.right, Load);
case UnaryOp_kind:
return validate_expr(exp->v.UnaryOp.operand, Load);
case Lambda_kind:
return validate_arguments(exp->v.Lambda.args) &&
validate_expr(exp->v.Lambda.body, Load);
case IfExp_kind:
return validate_expr(exp->v.IfExp.test, Load) &&
validate_expr(exp->v.IfExp.body, Load) &&
validate_expr(exp->v.IfExp.orelse, Load);
case Dict_kind:
if (asdl_seq_LEN(exp->v.Dict.keys) != asdl_seq_LEN(exp->v.Dict.values)) {
PyErr_SetString(PyExc_ValueError,
"Dict doesn't have the same number of keys as values");
return 0;
}
/* null_ok=1 for keys expressions to allow dict unpacking to work in
dict literals, i.e. ``{**{a:b}}`` */
return validate_exprs(exp->v.Dict.keys, Load, /*null_ok=*/ 1) &&
validate_exprs(exp->v.Dict.values, Load, /*null_ok=*/ 0);
case Set_kind:
return validate_exprs(exp->v.Set.elts, Load, 0);
#define COMP(NAME) \
case NAME ## _kind: \
return validate_comprehension(exp->v.NAME.generators) && \
validate_expr(exp->v.NAME.elt, Load);
COMP(ListComp)
COMP(SetComp)
COMP(GeneratorExp)
#undef COMP
case DictComp_kind:
return validate_comprehension(exp->v.DictComp.generators) &&
validate_expr(exp->v.DictComp.key, Load) &&
validate_expr(exp->v.DictComp.value, Load);
case Yield_kind:
return !exp->v.Yield.value || validate_expr(exp->v.Yield.value, Load);
case YieldFrom_kind:
return validate_expr(exp->v.YieldFrom.value, Load);
case Await_kind:
return validate_expr(exp->v.Await.value, Load);
case Compare_kind:
if (!asdl_seq_LEN(exp->v.Compare.comparators)) {
PyErr_SetString(PyExc_ValueError, "Compare with no comparators");
return 0;
}
if (asdl_seq_LEN(exp->v.Compare.comparators) !=
asdl_seq_LEN(exp->v.Compare.ops)) {
PyErr_SetString(PyExc_ValueError, "Compare has a different number "
"of comparators and operands");
return 0;
}
return validate_exprs(exp->v.Compare.comparators, Load, 0) &&
validate_expr(exp->v.Compare.left, Load);
case Call_kind:
return validate_expr(exp->v.Call.func, Load) &&
validate_exprs(exp->v.Call.args, Load, 0) &&
validate_keywords(exp->v.Call.keywords);
case Constant_kind:
if (!validate_constant(exp->v.Constant.value)) {
PyErr_Format(PyExc_TypeError,
"got an invalid type in Constant: %s",
Py_TYPE(exp->v.Constant.value)->tp_name);
return 0;
}
return 1;
case Num_kind: {
PyObject *n = exp->v.Num.n;
if (!PyLong_CheckExact(n) && !PyFloat_CheckExact(n) &&
!PyComplex_CheckExact(n)) {
PyErr_SetString(PyExc_TypeError, "non-numeric type in Num");
return 0;
}
return 1;
}
case Str_kind: {
PyObject *s = exp->v.Str.s;
if (!PyUnicode_CheckExact(s)) {
PyErr_SetString(PyExc_TypeError, "non-string type in Str");
return 0;
}
return 1;
}
case JoinedStr_kind:
return validate_exprs(exp->v.JoinedStr.values, Load, 0);
case FormattedValue_kind:
if (validate_expr(exp->v.FormattedValue.value, Load) == 0)
return 0;
if (exp->v.FormattedValue.format_spec)
return validate_expr(exp->v.FormattedValue.format_spec, Load);
return 1;
case Bytes_kind: {
PyObject *b = exp->v.Bytes.s;
if (!PyBytes_CheckExact(b)) {
PyErr_SetString(PyExc_TypeError, "non-bytes type in Bytes");
return 0;
}
return 1;
}
case Attribute_kind:
return validate_expr(exp->v.Attribute.value, Load);
case Subscript_kind:
return validate_slice(exp->v.Subscript.slice) &&
validate_expr(exp->v.Subscript.value, Load);
case Starred_kind:
return validate_expr(exp->v.Starred.value, ctx);
case List_kind:
return validate_exprs(exp->v.List.elts, ctx, 0);
case Tuple_kind:
return validate_exprs(exp->v.Tuple.elts, ctx, 0);
/* These last cases don't have any checking. */
case Name_kind:
case NameConstant_kind:
case Ellipsis_kind:
return 1;
default:
PyErr_SetString(PyExc_SystemError, "unexpected expression");
return 0;
}
}
static int
validate_nonempty_seq(asdl_seq *seq, const char *what, const char *owner)
{
if (asdl_seq_LEN(seq))
return 1;
PyErr_Format(PyExc_ValueError, "empty %s on %s", what, owner);
return 0;
}
static int
validate_assignlist(asdl_seq *targets, expr_context_ty ctx)
{
return validate_nonempty_seq(targets, "targets", ctx == Del ? "Delete" : "Assign") &&
validate_exprs(targets, ctx, 0);
}
static int
validate_body(asdl_seq *body, const char *owner)
{
return validate_nonempty_seq(body, "body", owner) && validate_stmts(body);
}
static int
validate_stmt(stmt_ty stmt)
{
int i;
switch (stmt->kind) {
case FunctionDef_kind:
return validate_body(stmt->v.FunctionDef.body, "FunctionDef") &&
validate_arguments(stmt->v.FunctionDef.args) &&
validate_exprs(stmt->v.FunctionDef.decorator_list, Load, 0) &&
(!stmt->v.FunctionDef.returns ||
validate_expr(stmt->v.FunctionDef.returns, Load));
case ClassDef_kind:
return validate_body(stmt->v.ClassDef.body, "ClassDef") &&
validate_exprs(stmt->v.ClassDef.bases, Load, 0) &&
validate_keywords(stmt->v.ClassDef.keywords) &&
validate_exprs(stmt->v.ClassDef.decorator_list, Load, 0);
case Return_kind:
return !stmt->v.Return.value || validate_expr(stmt->v.Return.value, Load);
case Delete_kind:
return validate_assignlist(stmt->v.Delete.targets, Del);
case Assign_kind:
return validate_assignlist(stmt->v.Assign.targets, Store) &&
validate_expr(stmt->v.Assign.value, Load);
case AugAssign_kind:
return validate_expr(stmt->v.AugAssign.target, Store) &&
validate_expr(stmt->v.AugAssign.value, Load);
case AnnAssign_kind:
if (stmt->v.AnnAssign.target->kind != Name_kind &&
stmt->v.AnnAssign.simple) {
PyErr_SetString(PyExc_TypeError,
"AnnAssign with simple non-Name target");
return 0;
}
return validate_expr(stmt->v.AnnAssign.target, Store) &&
(!stmt->v.AnnAssign.value ||
validate_expr(stmt->v.AnnAssign.value, Load)) &&
validate_expr(stmt->v.AnnAssign.annotation, Load);
case For_kind:
return validate_expr(stmt->v.For.target, Store) &&
validate_expr(stmt->v.For.iter, Load) &&
validate_body(stmt->v.For.body, "For") &&
validate_stmts(stmt->v.For.orelse);
case AsyncFor_kind:
return validate_expr(stmt->v.AsyncFor.target, Store) &&
validate_expr(stmt->v.AsyncFor.iter, Load) &&
validate_body(stmt->v.AsyncFor.body, "AsyncFor") &&
validate_stmts(stmt->v.AsyncFor.orelse);
case While_kind:
return validate_expr(stmt->v.While.test, Load) &&
validate_body(stmt->v.While.body, "While") &&
validate_stmts(stmt->v.While.orelse);
case If_kind:
return validate_expr(stmt->v.If.test, Load) &&
validate_body(stmt->v.If.body, "If") &&
validate_stmts(stmt->v.If.orelse);
case With_kind:
if (!validate_nonempty_seq(stmt->v.With.items, "items", "With"))
return 0;
for (i = 0; i < asdl_seq_LEN(stmt->v.With.items); i++) {
withitem_ty item = asdl_seq_GET(stmt->v.With.items, i);
if (!validate_expr(item->context_expr, Load) ||
(item->optional_vars && !validate_expr(item->optional_vars, Store)))
return 0;
}
return validate_body(stmt->v.With.body, "With");
case AsyncWith_kind:
if (!validate_nonempty_seq(stmt->v.AsyncWith.items, "items", "AsyncWith"))
return 0;
for (i = 0; i < asdl_seq_LEN(stmt->v.AsyncWith.items); i++) {
withitem_ty item = asdl_seq_GET(stmt->v.AsyncWith.items, i);
if (!validate_expr(item->context_expr, Load) ||
(item->optional_vars && !validate_expr(item->optional_vars, Store)))
return 0;
}
return validate_body(stmt->v.AsyncWith.body, "AsyncWith");
case Raise_kind:
if (stmt->v.Raise.exc) {
return validate_expr(stmt->v.Raise.exc, Load) &&
(!stmt->v.Raise.cause || validate_expr(stmt->v.Raise.cause, Load));
}
if (stmt->v.Raise.cause) {
PyErr_SetString(PyExc_ValueError, "Raise with cause but no exception");
return 0;
}
return 1;
case Try_kind:
if (!validate_body(stmt->v.Try.body, "Try"))
return 0;
if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
!asdl_seq_LEN(stmt->v.Try.finalbody)) {
PyErr_SetString(PyExc_ValueError, "Try has neither except handlers nor finalbody");
return 0;
}
if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
asdl_seq_LEN(stmt->v.Try.orelse)) {
PyErr_SetString(PyExc_ValueError, "Try has orelse but no except handlers");
return 0;
}
for (i = 0; i < asdl_seq_LEN(stmt->v.Try.handlers); i++) {
excepthandler_ty handler = asdl_seq_GET(stmt->v.Try.handlers, i);
if ((handler->v.ExceptHandler.type &&
!validate_expr(handler->v.ExceptHandler.type, Load)) ||
!validate_body(handler->v.ExceptHandler.body, "ExceptHandler"))
return 0;
}
return (!asdl_seq_LEN(stmt->v.Try.finalbody) ||
validate_stmts(stmt->v.Try.finalbody)) &&
(!asdl_seq_LEN(stmt->v.Try.orelse) ||
validate_stmts(stmt->v.Try.orelse));
case Assert_kind:
return validate_expr(stmt->v.Assert.test, Load) &&
(!stmt->v.Assert.msg || validate_expr(stmt->v.Assert.msg, Load));
case Import_kind:
return validate_nonempty_seq(stmt->v.Import.names, "names", "Import");
case ImportFrom_kind:
if (stmt->v.ImportFrom.level < 0) {
PyErr_SetString(PyExc_ValueError, "Negative ImportFrom level");
return 0;
}
return validate_nonempty_seq(stmt->v.ImportFrom.names, "names", "ImportFrom");
case Global_kind:
return validate_nonempty_seq(stmt->v.Global.names, "names", "Global");
case Nonlocal_kind:
return validate_nonempty_seq(stmt->v.Nonlocal.names, "names", "Nonlocal");
case Expr_kind:
return validate_expr(stmt->v.Expr.value, Load);
case AsyncFunctionDef_kind:
return validate_body(stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") &&
validate_arguments(stmt->v.AsyncFunctionDef.args) &&
validate_exprs(stmt->v.AsyncFunctionDef.decorator_list, Load, 0) &&
(!stmt->v.AsyncFunctionDef.returns ||
validate_expr(stmt->v.AsyncFunctionDef.returns, Load));
case Pass_kind:
case Break_kind:
case Continue_kind:
return 1;
default:
PyErr_SetString(PyExc_SystemError, "unexpected statement");
return 0;
}
}
static int
validate_stmts(asdl_seq *seq)
{
int i;
for (i = 0; i < asdl_seq_LEN(seq); i++) {
stmt_ty stmt = asdl_seq_GET(seq, i);
if (stmt) {
if (!validate_stmt(stmt))
return 0;
}
else {
PyErr_SetString(PyExc_ValueError,
"None disallowed in statement list");
return 0;
}
}
return 1;
}
static int
validate_exprs(asdl_seq *exprs, expr_context_ty ctx, int null_ok)
{
int i;
for (i = 0; i < asdl_seq_LEN(exprs); i++) {
expr_ty expr = asdl_seq_GET(exprs, i);
if (expr) {
if (!validate_expr(expr, ctx))
return 0;
}
else if (!null_ok) {
PyErr_SetString(PyExc_ValueError,
"None disallowed in expression list");
return 0;
}
}
return 1;
}
int
Ta3AST_Validate(mod_ty mod)
{
int res = 0;
switch (mod->kind) {
case Module_kind:
res = validate_stmts(mod->v.Module.body);
break;
case Interactive_kind:
res = validate_stmts(mod->v.Interactive.body);
break;
case Expression_kind:
res = validate_expr(mod->v.Expression.body, Load);
break;
case Suite_kind:
PyErr_SetString(PyExc_ValueError, "Suite is not valid in the CPython compiler");
break;
default:
PyErr_SetString(PyExc_SystemError, "impossible module node");
res = 0;
break;
}
return res;
}
/* This is done here, so defines like "test" don't interfere with AST use above. */
#include "grammar.h"
#include "parsetok.h"
#include "graminit.h"
/* Data structure used internally */
struct compiling {
PyArena *c_arena; /* Arena for allocating memory. */
PyObject *c_filename; /* filename */
PyObject *c_normalize; /* Normalization function from unicodedata. */
int c_feature_version; /* Latest minior version of Python for allowed features */
};
static asdl_seq *seq_for_testlist(struct compiling *, const node *);
static expr_ty ast_for_expr(struct compiling *, const node *);
static stmt_ty ast_for_stmt(struct compiling *, const node *);
static asdl_seq *ast_for_suite(struct compiling *c, const node *n);
static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
expr_context_ty);
static expr_ty ast_for_testlist(struct compiling *, const node *);
static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
static stmt_ty ast_for_with_stmt(struct compiling *, const node *, bool);
static stmt_ty ast_for_for_stmt(struct compiling *, const node *, bool);
/* Note different signature for ast_for_call */
static expr_ty ast_for_call(struct compiling *, const node *, expr_ty, bool);
static PyObject *parsenumber(struct compiling *, const char *);
static expr_ty parsestrplus(struct compiling *, const node *n);
#define COMP_GENEXP 0
#define COMP_LISTCOMP 1
#define COMP_SETCOMP 2
static int
init_normalization(struct compiling *c)
{
PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
if (!m)
return 0;
c->c_normalize = PyObject_GetAttrString(m, "normalize");
Py_DECREF(m);
if (!c->c_normalize)
return 0;
return 1;
}
static identifier
new_identifier(const char *n, struct compiling *c)
{
PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
if (!id)
return NULL;
/* PyUnicode_DecodeUTF8 should always return a ready string. */
assert(PyUnicode_IS_READY(id));
/* Check whether there are non-ASCII characters in the
identifier; if so, normalize to NFKC. */
if (!PyUnicode_IS_ASCII(id)) {
PyObject *id2;
PyObject *form;
PyObject *args[2];
_Py_IDENTIFIER(NFKC);
if (!c->c_normalize && !init_normalization(c)) {
Py_DECREF(id);
return NULL;
}
form = _PyUnicode_FromId(&PyId_NFKC);
if (form == NULL) {
Py_DECREF(id);
return NULL;
}
args[0] = form;
args[1] = id;
id2 = _PyObject_FastCall(c->c_normalize, args, 2);
Py_DECREF(id);
if (!id2)
return NULL;
if (!PyUnicode_Check(id2)) {
PyErr_Format(PyExc_TypeError,
"unicodedata.normalize() must return a string, not "
"%.200s",
Py_TYPE(id2)->tp_name);
Py_DECREF(id2);
return NULL;
}
id = id2;
}
PyUnicode_InternInPlace(&id);
if (PyArena_AddPyObject(c->c_arena, id) < 0) {
Py_DECREF(id);
return NULL;
}
return id;
}
#define NEW_IDENTIFIER(n) new_identifier(STR(n), c)
static string
new_type_comment(const char *s, struct compiling *c)
{
PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
if (!res)
return NULL;
if (PyArena_AddPyObject(c->c_arena, res) < 0) {
Py_DECREF(res);
return NULL;
}
return res;
}
#define NEW_TYPE_COMMENT(n) new_type_comment(STR(n), c)
static int
ast_error(struct compiling *c, const node *n, const char *errmsg)
{
PyObject *value, *errstr, *loc, *tmp;
loc = PyErr_ProgramTextObject(c->c_filename, LINENO(n));
if (!loc) {
Py_INCREF(Py_None);
loc = Py_None;
}
tmp = Py_BuildValue("(OiiN)", c->c_filename, LINENO(n), n->n_col_offset, loc);
if (!tmp)
return 0;
errstr = PyUnicode_FromString(errmsg);
if (!errstr) {
Py_DECREF(tmp);
return 0;
}
value = PyTuple_Pack(2, errstr, tmp);
Py_DECREF(errstr);
Py_DECREF(tmp);
if (value) {
PyErr_SetObject(PyExc_SyntaxError, value);
Py_DECREF(value);
}
return 0;
}
/* num_stmts() returns number of contained statements.
Use this routine to determine how big a sequence is needed for
the statements in a parse tree. Its raison d'etre is this bit of
grammar:
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
A simple_stmt can contain multiple small_stmt elements joined
by semicolons. If the arg is a simple_stmt, the number of
small_stmt elements is returned.
*/
static int
num_stmts(const node *n)
{
int i, l;
node *ch;
switch (TYPE(n)) {
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE)
return 0;
else
return num_stmts(CHILD(n, 0));
case file_input:
l = 0;
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == stmt)
l += num_stmts(ch);
}
return l;
case stmt:
return num_stmts(CHILD(n, 0));
case compound_stmt:
return 1;
case simple_stmt:
return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */
case suite:
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
if (NCH(n) == 1)
return num_stmts(CHILD(n, 0));
else {
i = 2;
l = 0;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++)
l += num_stmts(CHILD(n, i));
return l;
}
default: {
char buf[128];
sprintf(buf, "Non-statement found: %d %d",
TYPE(n), NCH(n));
Py_FatalError(buf);
}
}
abort();
}
/* Transform the CST rooted at node * to the appropriate AST
*/
mod_ty
Ta3AST_FromNodeObject(const node *n, PyCompilerFlags *flags,
PyObject *filename, int feature_version,
PyArena *arena)
{
int i, j, k, num;
asdl_seq *stmts = NULL;
asdl_seq *type_ignores = NULL;
stmt_ty s;
node *ch;
struct compiling c;
mod_ty res = NULL;
asdl_seq *argtypes = NULL;
expr_ty ret, arg;
c.c_arena = arena;
/* borrowed reference */
c.c_filename = filename;
c.c_normalize = NULL;
c.c_feature_version = feature_version;
if (TYPE(n) == encoding_decl)
n = CHILD(n, 0);
k = 0;
switch (TYPE(n)) {
case file_input:
stmts = _Ta3_asdl_seq_new(num_stmts(n), arena);
if (!stmts)
goto out;
for (i = 0; i < NCH(n) - 1; i++) {
ch = CHILD(n, i);
if (TYPE(ch) == NEWLINE)
continue;
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
s = ast_for_stmt(&c, ch);
if (!s)
goto out;
asdl_seq_SET(stmts, k++, s);
}
else {
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < num; j++) {
s = ast_for_stmt(&c, CHILD(ch, j * 2));
if (!s)
goto out;
asdl_seq_SET(stmts, k++, s);
}
}
}
/* Type ignores are stored under the ENDMARKER in file_input. */
ch = CHILD(n, NCH(n) - 1);
REQ(ch, ENDMARKER);
num = NCH(ch);
type_ignores = _Ta3_asdl_seq_new(num, arena);
if (!type_ignores)
goto out;
for (i = 0; i < num; i++) {
type_ignore_ty ti = TypeIgnore(LINENO(CHILD(ch, i)), arena);
if (!ti)
goto out;
asdl_seq_SET(type_ignores, i, ti);
}
res = Module(stmts, type_ignores, arena);
break;
case eval_input: {
expr_ty testlist_ast;
/* XXX Why not comp_for here? */
testlist_ast = ast_for_testlist(&c, CHILD(n, 0));
if (!testlist_ast)
goto out;
res = Expression(testlist_ast, arena);
break;
}
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE) {
stmts = _Ta3_asdl_seq_new(1, arena);
if (!stmts)
goto out;
asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
arena));
if (!asdl_seq_GET(stmts, 0))
goto out;
res = Interactive(stmts, arena);
}
else {
n = CHILD(n, 0);
num = num_stmts(n);
stmts = _Ta3_asdl_seq_new(num, arena);
if (!stmts)
goto out;
if (num == 1) {
s = ast_for_stmt(&c, n);
if (!s)
goto out;
asdl_seq_SET(stmts, 0, s);
}
else {
/* Only a simple_stmt can contain multiple statements. */
REQ(n, simple_stmt);
for (i = 0; i < NCH(n); i += 2) {
if (TYPE(CHILD(n, i)) == NEWLINE)
break;
s = ast_for_stmt(&c, CHILD(n, i));
if (!s)
goto out;
asdl_seq_SET(stmts, i / 2, s);
}
}
res = Interactive(stmts, arena);
}
break;
case func_type_input:
n = CHILD(n, 0);
REQ(n, func_type);
if (TYPE(CHILD(n, 1)) == typelist) {
ch = CHILD(n, 1);
/* this is overly permissive -- we don't pay any attention to
* stars on the args -- just parse them into an ordered list */
num = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test)
num++;
}
argtypes = _Ta3_asdl_seq_new(num, arena);
j = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test) {
arg = ast_for_expr(&c, CHILD(ch, i));
if (!arg)
goto out;
asdl_seq_SET(argtypes, j++, arg);
}
}
}
else
argtypes = _Ta3_asdl_seq_new(0, arena);
ret = ast_for_expr(&c, CHILD(n, NCH(n) - 1));
if (!ret)
goto out;
res = FunctionType(argtypes, ret, arena);
break;
default:
PyErr_Format(PyExc_SystemError,
"invalid node %d for Ta3AST_FromNode", TYPE(n));
goto out;
}
out:
if (c.c_normalize) {
Py_DECREF(c.c_normalize);
}
return res;
}
mod_ty
Ta3AST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename_str,
int feature_version, PyArena *arena)
{
mod_ty mod;
PyObject *filename;
filename = PyUnicode_DecodeFSDefault(filename_str);
if (filename == NULL)
return NULL;
mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena);
Py_DECREF(filename);
return mod;
}
/* Return the AST repr. of the operator represented as syntax (|, ^, etc.)
*/
static operator_ty
get_operator(struct compiling *c, const node *n)
{
switch (TYPE(n)) {
case VBAR:
return BitOr;
case CIRCUMFLEX:
return BitXor;
case AMPER:
return BitAnd;
case LEFTSHIFT:
return LShift;
case RIGHTSHIFT:
return RShift;
case PLUS:
return Add;
case MINUS:
return Sub;
case STAR:
return Mult;
case AT:
if (c->c_feature_version < 5) {
ast_error(c, n,
"The '@' operator is only supported in Python 3.5 and greater");
return (operator_ty)0;
}
return MatMult;
case SLASH:
return Div;
case DOUBLESLASH:
return FloorDiv;
case PERCENT:
return Mod;
default:
return (operator_ty)0;
}
}
static const char * const FORBIDDEN[] = {
"None",
"True",
"False",
NULL,
};
static int
forbidden_name(struct compiling *c, identifier name, const node *n,
int full_checks)
{
assert(PyUnicode_Check(name));
if (_PyUnicode_EqualToASCIIString(name, "__debug__")) {
ast_error(c, n, "assignment to keyword");
return 1;
}
if (full_checks) {
const char * const *p;
for (p = FORBIDDEN; *p; p++) {
if (_PyUnicode_EqualToASCIIString(name, *p)) {
ast_error(c, n, "assignment to keyword");
return 1;
}
}
}
return 0;
}
/* Set the context ctx for expr_ty e, recursively traversing e.
Only sets context for expr kinds that "can appear in assignment context"
(according to ../Parser/Python.asdl). For other expr kinds, it sets
an appropriate syntax error and returns false.
*/
static int
set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n)
{
asdl_seq *s = NULL;
/* If a particular expression type can't be used for assign / delete,
set expr_name to its name and an error message will be generated.
*/
const char* expr_name = NULL;
/* The ast defines augmented store and load contexts, but the
implementation here doesn't actually use them. The code may be
a little more complex than necessary as a result. It also means
that expressions in an augmented assignment have a Store context.
Consider restructuring so that augmented assignment uses
set_context(), too.
*/
assert(ctx != AugStore && ctx != AugLoad);
switch (e->kind) {
case Attribute_kind:
e->v.Attribute.ctx = ctx;
if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1))
return 0;
break;
case Subscript_kind:
e->v.Subscript.ctx = ctx;
break;
case Starred_kind:
e->v.Starred.ctx = ctx;
if (!set_context(c, e->v.Starred.value, ctx, n))
return 0;
break;
case Name_kind:
if (ctx == Store) {
if (forbidden_name(c, e->v.Name.id, n, 0))
return 0; /* forbidden_name() calls ast_error() */
}
e->v.Name.ctx = ctx;
break;
case List_kind:
e->v.List.ctx = ctx;
s = e->v.List.elts;
break;
case Tuple_kind:
e->v.Tuple.ctx = ctx;
s = e->v.Tuple.elts;
break;
case Lambda_kind:
expr_name = "lambda";
break;
case Call_kind:
expr_name = "function call";
break;
case BoolOp_kind:
case BinOp_kind:
case UnaryOp_kind:
expr_name = "operator";
break;
case GeneratorExp_kind:
expr_name = "generator expression";
break;
case Yield_kind:
case YieldFrom_kind:
expr_name = "yield expression";
break;
case Await_kind:
expr_name = "await expression";
break;
case ListComp_kind:
expr_name = "list comprehension";
break;
case SetComp_kind:
expr_name = "set comprehension";
break;
case DictComp_kind:
expr_name = "dict comprehension";
break;
case Dict_kind:
case Set_kind:
case Num_kind:
case Str_kind:
case Bytes_kind:
case JoinedStr_kind:
case FormattedValue_kind:
expr_name = "literal";
break;
case NameConstant_kind:
expr_name = "keyword";
break;
case Ellipsis_kind:
expr_name = "Ellipsis";
break;
case Compare_kind:
expr_name = "comparison";
break;
case IfExp_kind:
expr_name = "conditional expression";
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected expression in assignment %d (line %d)",
e->kind, e->lineno);
return 0;
}
/* Check for error string set by switch */
if (expr_name) {
char buf[300];
PyOS_snprintf(buf, sizeof(buf),
"can't %s %s",
ctx == Store ? "assign to" : "delete",
expr_name);
return ast_error(c, n, buf);
}
/* If the LHS is a list or tuple, we need to set the assignment
context for all the contained elements.
*/
if (s) {
int i;
for (i = 0; i < asdl_seq_LEN(s); i++) {
if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n))
return 0;
}
}
return 1;
}
static operator_ty
ast_for_augassign(struct compiling *c, const node *n)
{
REQ(n, augassign);
n = CHILD(n, 0);
switch (STR(n)[0]) {
case '+':
return Add;
case '-':
return Sub;
case '/':
if (STR(n)[1] == '/')
return FloorDiv;
else
return Div;
case '%':
return Mod;
case '<':
return LShift;
case '>':
return RShift;
case '&':
return BitAnd;
case '^':
return BitXor;
case '|':
return BitOr;
case '*':
if (STR(n)[1] == '*')
return Pow;
else
return Mult;
case '@':
if (c->c_feature_version < 5) {
ast_error(c, n,
"The '@' operator is only supported in Python 3.5 and greater");
return (operator_ty)0;
}
return MatMult;
default:
PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n));
return (operator_ty)0;
}
}
static cmpop_ty
ast_for_comp_op(struct compiling *c, const node *n)
{
/* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'
|'is' 'not'
*/
REQ(n, comp_op);
if (NCH(n) == 1) {
n = CHILD(n, 0);
switch (TYPE(n)) {
case LESS:
return Lt;
case GREATER:
return Gt;
case EQEQUAL: /* == */
return Eq;
case LESSEQUAL:
return LtE;
case GREATEREQUAL:
return GtE;
case NOTEQUAL:
return NotEq;
case NAME:
if (strcmp(STR(n), "in") == 0)
return In;
if (strcmp(STR(n), "is") == 0)
return Is;
/* fall through */
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s",
STR(n));
return (cmpop_ty)0;
}
}
else if (NCH(n) == 2) {
/* handle "not in" and "is not" */
switch (TYPE(CHILD(n, 0))) {
case NAME:
if (strcmp(STR(CHILD(n, 1)), "in") == 0)
return NotIn;
if (strcmp(STR(CHILD(n, 0)), "is") == 0)
return IsNot;
/* fall through */
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s",
STR(CHILD(n, 0)), STR(CHILD(n, 1)));
return (cmpop_ty)0;
}
}
PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children",
NCH(n));
return (cmpop_ty)0;
}
static asdl_seq *
seq_for_testlist(struct compiling *c, const node *n)
{
/* testlist: test (',' test)* [',']
testlist_star_expr: test|star_expr (',' test|star_expr)* [',']
*/
asdl_seq *seq;
expr_ty expression;
int i;
assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr || TYPE(n) == testlist_comp);
seq = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
const node *ch = CHILD(n, i);
assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr);
expression = ast_for_expr(c, ch);
if (!expression)
return NULL;
assert(i / 2 < seq->size);
asdl_seq_SET(seq, i / 2, expression);
}
return seq;
}
static arg_ty
ast_for_arg(struct compiling *c, const node *n)
{
identifier name;
expr_ty annotation = NULL;
node *ch;
arg_ty ret;
assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef);
ch = CHILD(n, 0);
name = NEW_IDENTIFIER(ch);
if (!name)
return NULL;
if (forbidden_name(c, name, ch, 0))
return NULL;
if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) {
annotation = ast_for_expr(c, CHILD(n, 2));
if (!annotation)
return NULL;
}
ret = arg(name, annotation, NULL, LINENO(n), n->n_col_offset, c->c_arena);
if (!ret)
return NULL;
return ret;
}
/* returns -1 if failed to handle keyword only arguments
returns new position to keep processing if successful
(',' tfpdef ['=' test])*
^^^
start pointing here
*/
static int
handle_keywordonly_args(struct compiling *c, const node *n, int start,
asdl_seq *kwonlyargs, asdl_seq *kwdefaults)
{
PyObject *argname;
node *ch;
expr_ty expression, annotation;
arg_ty arg = NULL;
int i = start;
int j = 0; /* index for kwdefaults and kwonlyargs */
if (kwonlyargs == NULL) {
ast_error(c, CHILD(n, start), "named arguments must follow bare *");
return -1;
}
assert(kwdefaults != NULL);
while (i < NCH(n)) {
ch = CHILD(n, i);
switch (TYPE(ch)) {
case vfpdef:
case tfpdef:
if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
expression = ast_for_expr(c, CHILD(n, i + 2));
if (!expression)
goto error;
asdl_seq_SET(kwdefaults, j, expression);
i += 2; /* '=' and test */
}
else { /* setting NULL if no default value exists */
asdl_seq_SET(kwdefaults, j, NULL);
}
if (NCH(ch) == 3) {
/* ch is NAME ':' test */
annotation = ast_for_expr(c, CHILD(ch, 2));
if (!annotation)
goto error;
}
else {
annotation = NULL;
}
ch = CHILD(ch, 0);
argname = NEW_IDENTIFIER(ch);
if (!argname)
goto error;
if (forbidden_name(c, argname, ch, 0))
goto error;
arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset,
c->c_arena);
if (!arg)
goto error;
asdl_seq_SET(kwonlyargs, j++, arg);
i += 1; /* the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case TYPE_COMMENT:
/* arg will be equal to the last argument processed */
arg->type_comment = NEW_TYPE_COMMENT(ch);
if (!arg->type_comment)
goto error;
i += 1;
break;
case DOUBLESTAR:
return i;
default:
ast_error(c, ch, "unexpected node");
goto error;
}
}
return i;
error:
return -1;
}
/* Create AST for argument list. */
static arguments_ty
ast_for_arguments(struct compiling *c, const node *n)
{
/* This function handles both typedargslist (function definition)
and varargslist (lambda definition).
parameters: '(' [typedargslist] ')'
typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [
'*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
| '**' tfpdef [',']]]
| '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
| '**' tfpdef [','])
tfpdef: NAME [':' test]
varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
'*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
| '**' vfpdef [',']]]
| '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
| '**' vfpdef [',']
)
vfpdef: NAME
*/
int i, j, k, nposargs = 0, nkwonlyargs = 0;
int nposdefaults = 0, found_default = 0;
asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults;
arg_ty vararg = NULL, kwarg = NULL;
arg_ty arg = NULL;
node *ch;
if (TYPE(n) == parameters) {
if (NCH(n) == 2) /* () as argument list */
return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena);
n = CHILD(n, 1);
}
assert(TYPE(n) == typedargslist || TYPE(n) == varargslist);
/* First count the number of positional args & defaults. The
variable i is the loop index for this for loop and the next.
The next loop picks up where the first leaves off.
*/
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == STAR) {
/* skip star */
i++;
if (i < NCH(n) && /* skip argument following star */
(TYPE(CHILD(n, i)) == tfpdef ||
TYPE(CHILD(n, i)) == vfpdef)) {
i++;
}
break;
}
if (TYPE(ch) == DOUBLESTAR) break;
if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++;
if (TYPE(ch) == EQUAL) nposdefaults++;
}
/* count the number of keyword only args &
defaults for keyword only args */
for ( ; i < NCH(n); ++i) {
ch = CHILD(n, i);
if (TYPE(ch) == DOUBLESTAR) break;
if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++;
}
posargs = (nposargs ? _Ta3_asdl_seq_new(nposargs, c->c_arena) : NULL);
if (!posargs && nposargs)
return NULL;
kwonlyargs = (nkwonlyargs ?
_Ta3_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
if (!kwonlyargs && nkwonlyargs)
return NULL;
posdefaults = (nposdefaults ?
_Ta3_asdl_seq_new(nposdefaults, c->c_arena) : NULL);
if (!posdefaults && nposdefaults)
return NULL;
/* The length of kwonlyargs and kwdefaults are same
since we set NULL as default for keyword only argument w/o default
- we have sequence data structure, but no dictionary */
kwdefaults = (nkwonlyargs ?
_Ta3_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
if (!kwdefaults && nkwonlyargs)
return NULL;
/* tfpdef: NAME [':' test]
vfpdef: NAME
*/
i = 0;
j = 0; /* index for defaults */
k = 0; /* index for args */
while (i < NCH(n)) {
ch = CHILD(n, i);
switch (TYPE(ch)) {
case tfpdef:
case vfpdef:
/* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is
anything other than EQUAL or a comma? */
/* XXX Should NCH(n) check be made a separate check? */
if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
expr_ty expression = ast_for_expr(c, CHILD(n, i + 2));
if (!expression)
return NULL;
assert(posdefaults != NULL);
asdl_seq_SET(posdefaults, j++, expression);
i += 2;
found_default = 1;
}
else if (found_default) {
ast_error(c, n,
"non-default argument follows default argument");
return NULL;
}
arg = ast_for_arg(c, ch);
if (!arg)
return NULL;
asdl_seq_SET(posargs, k++, arg);
i += 1; /* the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case STAR:
if (i+1 >= NCH(n) ||
(i+2 == NCH(n) && (TYPE(CHILD(n, i+1)) == COMMA
|| TYPE(CHILD(n, i+1)) == TYPE_COMMENT))) {
ast_error(c, CHILD(n, i),
"named arguments must follow bare *");
return NULL;
}
ch = CHILD(n, i+1); /* tfpdef or COMMA */
if (TYPE(ch) == COMMA) {
int res = 0;
i += 2; /* now follows keyword only arguments */
if (i < NCH(n) && TYPE(CHILD(n, i)) == TYPE_COMMENT) {
ast_error(c, CHILD(n, i),
"bare * has associated type comment");
return NULL;
}
res = handle_keywordonly_args(c, n, i,
kwonlyargs, kwdefaults);
if (res == -1) return NULL;
i = res; /* res has new position to process */
}
else {
vararg = ast_for_arg(c, ch);
if (!vararg)
return NULL;
i += 2; /* the star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
if (i < NCH(n) && TYPE(CHILD(n, i)) == TYPE_COMMENT) {
vararg->type_comment = NEW_TYPE_COMMENT(CHILD(n, i));
if (!vararg->type_comment)
return NULL;
i += 1;
}
if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef
|| TYPE(CHILD(n, i)) == vfpdef)) {
int res = 0;
res = handle_keywordonly_args(c, n, i,
kwonlyargs, kwdefaults);
if (res == -1) return NULL;
i = res; /* res has new position to process */
}
}
break;
case DOUBLESTAR:
ch = CHILD(n, i+1); /* tfpdef */
assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef);
kwarg = ast_for_arg(c, ch);
if (!kwarg)
return NULL;
i += 2; /* the double star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case TYPE_COMMENT:
assert(i);
if (kwarg)
arg = kwarg;
/* arg will be equal to the last argument processed */
arg->type_comment = NEW_TYPE_COMMENT(ch);
if (!arg->type_comment)
return NULL;
i += 1;
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected node in varargslist: %d @ %d",
TYPE(ch), i);
return NULL;
}
}
return arguments(posargs, vararg, kwonlyargs, kwdefaults, kwarg, posdefaults, c->c_arena);
}
static expr_ty
ast_for_dotted_name(struct compiling *c, const node *n)
{
expr_ty e;
identifier id;
int lineno, col_offset;
int i;
REQ(n, dotted_name);
lineno = LINENO(n);
col_offset = n->n_col_offset;
id = NEW_IDENTIFIER(CHILD(n, 0));
if (!id)
return NULL;
e = Name(id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
for (i = 2; i < NCH(n); i+=2) {
id = NEW_IDENTIFIER(CHILD(n, i));
if (!id)
return NULL;
e = Attribute(e, id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
}
return e;
}
static expr_ty
ast_for_decorator(struct compiling *c, const node *n)
{
/* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */
expr_ty d = NULL;
expr_ty name_expr;
REQ(n, decorator);
REQ(CHILD(n, 0), AT);
REQ(RCHILD(n, -1), NEWLINE);
name_expr = ast_for_dotted_name(c, CHILD(n, 1));
if (!name_expr)
return NULL;
if (NCH(n) == 3) { /* No arguments */
d = name_expr;
name_expr = NULL;
}
else if (NCH(n) == 5) { /* Call with no arguments */
d = Call(name_expr, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
if (!d)
return NULL;
name_expr = NULL;
}
else {
d = ast_for_call(c, CHILD(n, 3), name_expr, true);
if (!d)
return NULL;
name_expr = NULL;
}
return d;
}
static asdl_seq*
ast_for_decorators(struct compiling *c, const node *n)
{
asdl_seq* decorator_seq;
expr_ty d;
int i;
REQ(n, decorators);
decorator_seq = _Ta3_asdl_seq_new(NCH(n), c->c_arena);
if (!decorator_seq)
return NULL;
for (i = 0; i < NCH(n); i++) {
d = ast_for_decorator(c, CHILD(n, i));
if (!d)
return NULL;
asdl_seq_SET(decorator_seq, i, d);
}
return decorator_seq;
}
static stmt_ty
ast_for_funcdef_impl(struct compiling *c, const node *n0,
asdl_seq *decorator_seq, bool is_async)
{
/* funcdef: 'def' NAME parameters ['->' test] ':' [TYPE_COMMENT] suite */
const node * const n = is_async ? CHILD(n0, 1) : n0;
identifier name;
arguments_ty args;
asdl_seq *body;
expr_ty returns = NULL;
int name_i = 1;
node *tc;
string type_comment = NULL;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async functions are only supported in Python 3.5 and greater");
return NULL;
}
REQ(n, funcdef);
name = NEW_IDENTIFIER(CHILD(n, name_i));
if (!name)
return NULL;
if (forbidden_name(c, name, CHILD(n, name_i), 0))
return NULL;
args = ast_for_arguments(c, CHILD(n, name_i + 1));
if (!args)
return NULL;
if (TYPE(CHILD(n, name_i+2)) == RARROW) {
returns = ast_for_expr(c, CHILD(n, name_i + 3));
if (!returns)
return NULL;
name_i += 2;
}
if (TYPE(CHILD(n, name_i + 3)) == TYPE_COMMENT) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, name_i + 3));
if (!type_comment)
return NULL;
name_i += 1;
}
body = ast_for_suite(c, CHILD(n, name_i + 3));
if (!body)
return NULL;
if (NCH(CHILD(n, name_i + 3)) > 1) {
/* Check if the suite has a type comment in it. */
tc = CHILD(CHILD(n, name_i + 3), 1);
if (TYPE(tc) == TYPE_COMMENT) {
if (type_comment != NULL) {
ast_error(c, n, "Cannot have two type comments on def");
return NULL;
}
type_comment = NEW_TYPE_COMMENT(tc);
if (!type_comment)
return NULL;
}
}
if (is_async)
return AsyncFunctionDef(name, args, body, decorator_seq, returns,
type_comment, LINENO(n0), n0->n_col_offset, c->c_arena);
else
return FunctionDef(name, args, body, decorator_seq, returns,
type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* async_funcdef: 'async' funcdef */
REQ(n, async_funcdef);
REQ(CHILD(n, 0), ASYNC);
REQ(CHILD(n, 1), funcdef);
return ast_for_funcdef_impl(c, n, decorator_seq,
true /* is_async */);
}
static stmt_ty
ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* funcdef: 'def' NAME parameters ['->' test] ':' suite */
return ast_for_funcdef_impl(c, n, decorator_seq,
false /* is_async */);
}
static stmt_ty
ast_for_async_stmt(struct compiling *c, const node *n)
{
/* async_stmt: 'async' (funcdef | with_stmt | for_stmt) */
REQ(n, async_stmt);
REQ(CHILD(n, 0), ASYNC);
switch (TYPE(CHILD(n, 1))) {
case funcdef:
return ast_for_funcdef_impl(c, n, NULL,
true /* is_async */);
case with_stmt:
return ast_for_with_stmt(c, n,
true /* is_async */);
case for_stmt:
return ast_for_for_stmt(c, n,
true /* is_async */);
default:
PyErr_Format(PyExc_SystemError,
"invalid async stament: %s",
STR(CHILD(n, 1)));
return NULL;
}
}
static stmt_ty
ast_for_decorated(struct compiling *c, const node *n)
{
/* decorated: decorators (classdef | funcdef | async_funcdef) */
stmt_ty thing = NULL;
asdl_seq *decorator_seq = NULL;
REQ(n, decorated);
decorator_seq = ast_for_decorators(c, CHILD(n, 0));
if (!decorator_seq)
return NULL;
assert(TYPE(CHILD(n, 1)) == funcdef ||
TYPE(CHILD(n, 1)) == async_funcdef ||
TYPE(CHILD(n, 1)) == classdef);
if (TYPE(CHILD(n, 1)) == funcdef) {
thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == classdef) {
thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == async_funcdef) {
thing = ast_for_async_funcdef(c, CHILD(n, 1), decorator_seq);
}
/* we count the decorators in when talking about the class' or
* function's line number */
if (thing) {
thing->lineno = LINENO(n);
thing->col_offset = n->n_col_offset;
}
return thing;
}
static expr_ty
ast_for_lambdef(struct compiling *c, const node *n)
{
/* lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond */
arguments_ty args;
expr_ty expression;
if (NCH(n) == 3) {
args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena);
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
}
else {
args = ast_for_arguments(c, CHILD(n, 1));
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 3));
if (!expression)
return NULL;
}
return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_ifexpr(struct compiling *c, const node *n)
{
/* test: or_test 'if' or_test 'else' test */
expr_ty expression, body, orelse;
assert(NCH(n) == 5);
body = ast_for_expr(c, CHILD(n, 0));
if (!body)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
orelse = ast_for_expr(c, CHILD(n, 4));
if (!orelse)
return NULL;
return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset,
c->c_arena);
}
/*
Count the number of 'for' loops in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_fors(struct compiling *c, const node *n)
{
int n_fors = 0;
count_comp_for:
n_fors++;
REQ(n, comp_for);
if (NCH(n) == 2) {
REQ(CHILD(n, 0), ASYNC);
n = CHILD(n, 1);
}
else if (NCH(n) == 1) {
n = CHILD(n, 0);
}
else {
goto error;
}
if (NCH(n) == (5)) {
n = CHILD(n, 4);
}
else {
return n_fors;
}
count_comp_iter:
REQ(n, comp_iter);
n = CHILD(n, 0);
if (TYPE(n) == comp_for)
goto count_comp_for;
else if (TYPE(n) == comp_if) {
if (NCH(n) == 3) {
n = CHILD(n, 2);
goto count_comp_iter;
}
else
return n_fors;
}
error:
/* Should never be reached */
PyErr_SetString(PyExc_SystemError,
"logic error in count_comp_fors");
return -1;
}
/* Count the number of 'if' statements in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_ifs(struct compiling *c, const node *n)
{
int n_ifs = 0;
while (1) {
REQ(n, comp_iter);
if (TYPE(CHILD(n, 0)) == comp_for)
return n_ifs;
n = CHILD(n, 0);
REQ(n, comp_if);
n_ifs++;
if (NCH(n) == 2)
return n_ifs;
n = CHILD(n, 2);
}
}
static asdl_seq *
ast_for_comprehension(struct compiling *c, const node *n)
{
int i, n_fors;
asdl_seq *comps;
n_fors = count_comp_fors(c, n);
if (n_fors == -1)
return NULL;
comps = _Ta3_asdl_seq_new(n_fors, c->c_arena);
if (!comps)
return NULL;
for (i = 0; i < n_fors; i++) {
comprehension_ty comp;
asdl_seq *t;
expr_ty expression, first;
node *for_ch;
node *sync_n;
int is_async = 0;
REQ(n, comp_for);
if (NCH(n) == 2) {
is_async = 1;
REQ(CHILD(n, 0), ASYNC);
sync_n = CHILD(n, 1);
}
else {
sync_n = CHILD(n, 0);
}
REQ(sync_n, sync_comp_for);
/* Async comprehensions only allowed in Python 3.6 and greater */
if (is_async && c->c_feature_version < 6) {
ast_error(c, n,
"Async comprehensions are only supported in Python 3.6 and greater");
return NULL;
}
for_ch = CHILD(sync_n, 1);
t = ast_for_exprlist(c, for_ch, Store);
if (!t)
return NULL;
expression = ast_for_expr(c, CHILD(sync_n, 3));
if (!expression)
return NULL;
/* Check the # of children rather than the length of t, since
(x for x, in ...) has 1 element in t, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(t, 0);
if (NCH(for_ch) == 1)
comp = comprehension(first, expression, NULL,
is_async, c->c_arena);
else
comp = comprehension(Tuple(t, Store, first->lineno,
first->col_offset, c->c_arena),
expression, NULL, is_async, c->c_arena);
if (!comp)
return NULL;
if (NCH(sync_n) == 5) {
int j, n_ifs;
asdl_seq *ifs;
n = CHILD(sync_n, 4);
n_ifs = count_comp_ifs(c, n);
if (n_ifs == -1)
return NULL;
ifs = _Ta3_asdl_seq_new(n_ifs, c->c_arena);
if (!ifs)
return NULL;
for (j = 0; j < n_ifs; j++) {
REQ(n, comp_iter);
n = CHILD(n, 0);
REQ(n, comp_if);
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
asdl_seq_SET(ifs, j, expression);
if (NCH(n) == 3)
n = CHILD(n, 2);
}
/* on exit, must guarantee that n is a comp_for */
if (TYPE(n) == comp_iter)
n = CHILD(n, 0);
comp->ifs = ifs;
}
asdl_seq_SET(comps, i, comp);
}
return comps;
}
static expr_ty
ast_for_itercomp(struct compiling *c, const node *n, int type)
{
/* testlist_comp: (test|star_expr)
* ( comp_for | (',' (test|star_expr))* [','] ) */
expr_ty elt;
asdl_seq *comps;
node *ch;
assert(NCH(n) > 1);
ch = CHILD(n, 0);
elt = ast_for_expr(c, ch);
if (!elt)
return NULL;
if (elt->kind == Starred_kind) {
ast_error(c, ch, "iterable unpacking cannot be used in comprehension");
return NULL;
}
comps = ast_for_comprehension(c, CHILD(n, 1));
if (!comps)
return NULL;
if (type == COMP_GENEXP)
return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else if (type == COMP_LISTCOMP)
return ListComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else if (type == COMP_SETCOMP)
return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else
/* Should never happen */
return NULL;
}
/* Fills in the key, value pair corresponding to the dict element. In case
* of an unpacking, key is NULL. *i is advanced by the number of ast
* elements. Iff successful, nonzero is returned.
*/
static int
ast_for_dictelement(struct compiling *c, const node *n, int *i,
expr_ty *key, expr_ty *value)
{
expr_ty expression;
if (TYPE(CHILD(n, *i)) == DOUBLESTAR) {
assert(NCH(n) - *i >= 2);
expression = ast_for_expr(c, CHILD(n, *i + 1));
if (!expression)
return 0;
*key = NULL;
*value = expression;
*i += 2;
}
else {
assert(NCH(n) - *i >= 3);
expression = ast_for_expr(c, CHILD(n, *i));
if (!expression)
return 0;
*key = expression;
REQ(CHILD(n, *i + 1), COLON);
expression = ast_for_expr(c, CHILD(n, *i + 2));
if (!expression)
return 0;
*value = expression;
*i += 3;
}
return 1;
}
static expr_ty
ast_for_dictcomp(struct compiling *c, const node *n)
{
expr_ty key, value;
asdl_seq *comps;
int i = 0;
if (!ast_for_dictelement(c, n, &i, &key, &value))
return NULL;
assert(key);
assert(NCH(n) - i >= 1);
comps = ast_for_comprehension(c, CHILD(n, i));
if (!comps)
return NULL;
return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_dictdisplay(struct compiling *c, const node *n)
{
int i;
int j;
int size;
asdl_seq *keys, *values;
size = (NCH(n) + 1) / 3; /* +1 in case no trailing comma */
keys = _Ta3_asdl_seq_new(size, c->c_arena);
if (!keys)
return NULL;
values = _Ta3_asdl_seq_new(size, c->c_arena);
if (!values)
return NULL;
j = 0;
for (i = 0; i < NCH(n); i++) {
expr_ty key, value;
if (!ast_for_dictelement(c, n, &i, &key, &value))
return NULL;
asdl_seq_SET(keys, j, key);
asdl_seq_SET(values, j, value);
j++;
}
keys->size = j;
values->size = j;
return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_genexp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument));
return ast_for_itercomp(c, n, COMP_GENEXP);
}
static expr_ty
ast_for_listcomp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (testlist_comp));
return ast_for_itercomp(c, n, COMP_LISTCOMP);
}
static expr_ty
ast_for_setcomp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (dictorsetmaker));
return ast_for_itercomp(c, n, COMP_SETCOMP);
}
static expr_ty
ast_for_setdisplay(struct compiling *c, const node *n)
{
int i;
int size;
asdl_seq *elts;
assert(TYPE(n) == (dictorsetmaker));
size = (NCH(n) + 1) / 2; /* +1 in case no trailing comma */
elts = _Ta3_asdl_seq_new(size, c->c_arena);
if (!elts)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
expr_ty expression;
expression = ast_for_expr(c, CHILD(n, i));
if (!expression)
return NULL;
asdl_seq_SET(elts, i / 2, expression);
}
return Set(elts, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_atom(struct compiling *c, const node *n)
{
/* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']'
| '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+
| '...' | 'None' | 'True' | 'False'
*/
node *ch = CHILD(n, 0);
switch (TYPE(ch)) {
case NAME: {
PyObject *name;
const char *s = STR(ch);
size_t len = strlen(s);
if (len >= 4 && len <= 5) {
if (!strcmp(s, "None"))
return NameConstant(Py_None, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "True"))
return NameConstant(Py_True, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "False"))
return NameConstant(Py_False, LINENO(n), n->n_col_offset, c->c_arena);
}
name = new_identifier(s, c);
if (!name)
return NULL;
/* All names start in Load context, but may later be changed. */
return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
case STRING: {
expr_ty str = parsestrplus(c, n);
if (!str) {
const char *errtype = NULL;
if (PyErr_ExceptionMatches(PyExc_UnicodeError))
errtype = "unicode error";
else if (PyErr_ExceptionMatches(PyExc_ValueError))
errtype = "value error";
if (errtype) {
char buf[128];
const char *s = NULL;
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr)
s = PyUnicode_AsUTF8(errstr);
if (s) {
PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s);
} else {
PyErr_Clear();
PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype);
}
Py_XDECREF(errstr);
ast_error(c, n, buf);
Py_DECREF(type);
Py_XDECREF(value);
Py_XDECREF(tback);
}
return NULL;
}
return str;
}
case NUMBER: {
PyObject *pynum;
const char *s = STR(ch);
/* Underscores in numeric literals are only allowed in Python 3.6 or greater */
/* Check for underscores here rather than in parse_number so we can report a line number on error */
if (c->c_feature_version < 6 && strchr(s, '_') != NULL) {
ast_error(c, ch,
"Underscores in numeric literals are only supported in Python 3.6 and greater");
return NULL;
}
pynum = parsenumber(c, STR(ch));
if (!pynum)
return NULL;
if (PyArena_AddPyObject(c->c_arena, pynum) < 0) {
Py_DECREF(pynum);
return NULL;
}
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
case ELLIPSIS: /* Ellipsis */
return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena);
case LPAR: /* some parenthesized expressions */
ch = CHILD(n, 1);
if (TYPE(ch) == RPAR)
return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (TYPE(ch) == yield_expr)
return ast_for_expr(c, ch);
/* testlist_comp: test ( comp_for | (',' test)* [','] ) */
if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for))
return ast_for_genexp(c, ch);
return ast_for_testlist(c, ch);
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
REQ(ch, testlist_comp);
if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
asdl_seq *elts = seq_for_testlist(c, ch);
if (!elts)
return NULL;
return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
else
return ast_for_listcomp(c, ch);
case LBRACE: {
/* dictorsetmaker: ( ((test ':' test | '**' test)
* (comp_for | (',' (test ':' test | '**' test))* [','])) |
* ((test | '*' test)
* (comp_for | (',' (test | '*' test))* [','])) ) */
expr_ty res;
ch = CHILD(n, 1);
if (TYPE(ch) == RBRACE) {
/* It's an empty dict. */
return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR);
if (NCH(ch) == 1 ||
(NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == COMMA)) {
/* It's a set display. */
res = ast_for_setdisplay(c, ch);
}
else if (NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == comp_for) {
/* It's a set comprehension. */
res = ast_for_setcomp(c, ch);
}
else if (NCH(ch) > 3 - is_dict &&
TYPE(CHILD(ch, 3 - is_dict)) == comp_for) {
/* It's a dictionary comprehension. */
if (is_dict) {
ast_error(c, n, "dict unpacking cannot be used in "
"dict comprehension");
return NULL;
}
res = ast_for_dictcomp(c, ch);
}
else {
/* It's a dictionary display. */
res = ast_for_dictdisplay(c, ch);
}
if (res) {
res->lineno = LINENO(n);
res->col_offset = n->n_col_offset;
}
return res;
}
}
default:
PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
return NULL;
}
}
static slice_ty
ast_for_slice(struct compiling *c, const node *n)
{
node *ch;
expr_ty lower = NULL, upper = NULL, step = NULL;
REQ(n, subscript);
/*
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
*/
ch = CHILD(n, 0);
if (NCH(n) == 1 && TYPE(ch) == test) {
/* 'step' variable hold no significance in terms of being used over
other vars */
step = ast_for_expr(c, ch);
if (!step)
return NULL;
return Index(step, c->c_arena);
}
if (TYPE(ch) == test) {
lower = ast_for_expr(c, ch);
if (!lower)
return NULL;
}
/* If there's an upper bound it's in the second or third position. */
if (TYPE(ch) == COLON) {
if (NCH(n) > 1) {
node *n2 = CHILD(n, 1);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
} else if (NCH(n) > 2) {
node *n2 = CHILD(n, 2);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
ch = CHILD(n, NCH(n) - 1);
if (TYPE(ch) == sliceop) {
if (NCH(ch) != 1) {
ch = CHILD(ch, 1);
if (TYPE(ch) == test) {
step = ast_for_expr(c, ch);
if (!step)
return NULL;
}
}
}
return Slice(lower, upper, step, c->c_arena);
}
static expr_ty
ast_for_binop(struct compiling *c, const node *n)
{
/* Must account for a sequence of expressions.
How should A op B op C by represented?
BinOp(BinOp(A, op, B), op, C).
*/
int i, nops;
expr_ty expr1, expr2, result;
operator_ty newoperator;
expr1 = ast_for_expr(c, CHILD(n, 0));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 2));
if (!expr2)
return NULL;
newoperator = get_operator(c, CHILD(n, 1));
if (!newoperator)
return NULL;
result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
c->c_arena);
if (!result)
return NULL;
nops = (NCH(n) - 1) / 2;
for (i = 1; i < nops; i++) {
expr_ty tmp_result, tmp;
const node* next_oper = CHILD(n, i * 2 + 1);
newoperator = get_operator(c, next_oper);
if (!newoperator)
return NULL;
tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
if (!tmp)
return NULL;
tmp_result = BinOp(result, newoperator, tmp,
LINENO(next_oper), next_oper->n_col_offset,
c->c_arena);
if (!tmp_result)
return NULL;
result = tmp_result;
}
return result;
}
static expr_ty
ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr)
{
/* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
*/
REQ(n, trailer);
if (TYPE(CHILD(n, 0)) == LPAR) {
if (NCH(n) == 2)
return Call(left_expr, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
else
return ast_for_call(c, CHILD(n, 1), left_expr, true);
}
else if (TYPE(CHILD(n, 0)) == DOT) {
PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1));
if (!attr_id)
return NULL;
return Attribute(left_expr, attr_id, Load,
LINENO(n), n->n_col_offset, c->c_arena);
}
else {
REQ(CHILD(n, 0), LSQB);
REQ(CHILD(n, 2), RSQB);
n = CHILD(n, 1);
if (NCH(n) == 1) {
slice_ty slc = ast_for_slice(c, CHILD(n, 0));
if (!slc)
return NULL;
return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset,
c->c_arena);
}
else {
/* The grammar is ambiguous here. The ambiguity is resolved
by treating the sequence as a tuple literal if there are
no slice features.
*/
int j;
slice_ty slc;
expr_ty e;
int simple = 1;
asdl_seq *slices, *elts;
slices = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!slices)
return NULL;
for (j = 0; j < NCH(n); j += 2) {
slc = ast_for_slice(c, CHILD(n, j));
if (!slc)
return NULL;
if (slc->kind != Index_kind)
simple = 0;
asdl_seq_SET(slices, j / 2, slc);
}
if (!simple) {
return Subscript(left_expr, ExtSlice(slices, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
/* extract Index values and put them in a Tuple */
elts = _Ta3_asdl_seq_new(asdl_seq_LEN(slices), c->c_arena);
if (!elts)
return NULL;
for (j = 0; j < asdl_seq_LEN(slices); ++j) {
slc = (slice_ty)asdl_seq_GET(slices, j);
assert(slc->kind == Index_kind && slc->v.Index.value);
asdl_seq_SET(elts, j, slc->v.Index.value);
}
e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (!e)
return NULL;
return Subscript(left_expr, Index(e, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
}
static expr_ty
ast_for_factor(struct compiling *c, const node *n)
{
expr_ty expression;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
switch (TYPE(CHILD(n, 0))) {
case PLUS:
return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case MINUS:
return UnaryOp(USub, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case TILDE:
return UnaryOp(Invert, expression, LINENO(n),
n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError, "unhandled factor: %d",
TYPE(CHILD(n, 0)));
return NULL;
}
static expr_ty
ast_for_atom_expr(struct compiling *c, const node *n)
{
int i, nch, start = 0;
expr_ty e, tmp;
REQ(n, atom_expr);
nch = NCH(n);
if (TYPE(CHILD(n, 0)) == AWAIT) {
if (c->c_feature_version < 5) {
ast_error(c, n,
"Await expressions are only supported in Python 3.5 and greater");
return NULL;
}
start = 1;
assert(nch > 1);
}
e = ast_for_atom(c, CHILD(n, start));
if (!e)
return NULL;
if (nch == 1)
return e;
if (start && nch == 2) {
return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
}
for (i = start + 1; i < nch; i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) != trailer)
break;
tmp = ast_for_trailer(c, ch, e);
if (!tmp)
return NULL;
tmp->lineno = e->lineno;
tmp->col_offset = e->col_offset;
e = tmp;
}
if (start) {
/* there was an 'await' */
return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
return e;
}
}
static expr_ty
ast_for_power(struct compiling *c, const node *n)
{
/* power: atom trailer* ('**' factor)*
*/
expr_ty e;
REQ(n, power);
e = ast_for_atom_expr(c, CHILD(n, 0));
if (!e)
return NULL;
if (NCH(n) == 1)
return e;
if (TYPE(CHILD(n, NCH(n) - 1)) == factor) {
expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1));
if (!f)
return NULL;
e = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena);
}
return e;
}
static expr_ty
ast_for_starred(struct compiling *c, const node *n)
{
expr_ty tmp;
REQ(n, star_expr);
tmp = ast_for_expr(c, CHILD(n, 1));
if (!tmp)
return NULL;
/* The Load context is changed later. */
return Starred(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
/* Do not name a variable 'expr'! Will cause a compile error.
*/
static expr_ty
ast_for_expr(struct compiling *c, const node *n)
{
/* handle the full range of simple expressions
test: or_test ['if' or_test 'else' test] | lambdef
test_nocond: or_test | lambdef_nocond
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom_expr ['**' factor]
atom_expr: ['await'] atom trailer*
yield_expr: 'yield' [yield_arg]
*/
asdl_seq *seq;
int i;
loop:
switch (TYPE(n)) {
case test:
case test_nocond:
if (TYPE(CHILD(n, 0)) == lambdef ||
TYPE(CHILD(n, 0)) == lambdef_nocond)
return ast_for_lambdef(c, CHILD(n, 0));
else if (NCH(n) > 1)
return ast_for_ifexpr(c, n);
/* Fallthrough */
case or_test:
case and_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
seq = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
expr_ty e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
}
if (!strcmp(STR(CHILD(n, 1)), "and"))
return BoolOp(And, seq, LINENO(n), n->n_col_offset,
c->c_arena);
assert(!strcmp(STR(CHILD(n, 1)), "or"));
return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena);
case not_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return UnaryOp(Not, expression, LINENO(n), n->n_col_offset,
c->c_arena);
}
case comparison:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression;
asdl_int_seq *ops;
asdl_seq *cmps;
ops = _Ta3_asdl_int_seq_new(NCH(n) / 2, c->c_arena);
if (!ops)
return NULL;
cmps = _Ta3_asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!cmps) {
return NULL;
}
for (i = 1; i < NCH(n); i += 2) {
cmpop_ty newoperator;
newoperator = ast_for_comp_op(c, CHILD(n, i));
if (!newoperator) {
return NULL;
}
expression = ast_for_expr(c, CHILD(n, i + 1));
if (!expression) {
return NULL;
}
asdl_seq_SET(ops, i / 2, newoperator);
asdl_seq_SET(cmps, i / 2, expression);
}
expression = ast_for_expr(c, CHILD(n, 0));
if (!expression) {
return NULL;
}
return Compare(expression, ops, cmps, LINENO(n),
n->n_col_offset, c->c_arena);
}
break;
case star_expr:
return ast_for_starred(c, n);
/* The next five cases all handle BinOps. The main body of code
is the same in each case, but the switch turned inside out to
reuse the code for each type of operator.
*/
case expr:
case xor_expr:
case and_expr:
case shift_expr:
case arith_expr:
case term:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_binop(c, n);
case yield_expr: {
node *an = NULL;
node *en = NULL;
int is_from = 0;
expr_ty exp = NULL;
if (NCH(n) > 1)
an = CHILD(n, 1); /* yield_arg */
if (an) {
en = CHILD(an, NCH(an) - 1);
if (NCH(an) == 2) {
is_from = 1;
exp = ast_for_expr(c, en);
}
else
exp = ast_for_testlist(c, en);
if (!exp)
return NULL;
}
if (is_from)
return YieldFrom(exp, LINENO(n), n->n_col_offset, c->c_arena);
return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case factor:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_factor(c, n);
case power:
return ast_for_power(c, n);
default:
PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n));
return NULL;
}
/* should never get here unless if error is set */
return NULL;
}
static expr_ty
ast_for_call(struct compiling *c, const node *n, expr_ty func, bool allowgen)
{
/*
arglist: argument (',' argument)* [',']
argument: ( test [comp_for] | '*' test | test '=' test | '**' test )
*/
int i, nargs, nkeywords;
int ndoublestars;
asdl_seq *args;
asdl_seq *keywords;
REQ(n, arglist);
nargs = 0;
nkeywords = 0;
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
if (NCH(ch) == 1)
nargs++;
else if (TYPE(CHILD(ch, 1)) == comp_for) {
nargs++;
if (!allowgen) {
ast_error(c, ch, "invalid syntax");
return NULL;
}
if (NCH(n) > 1) {
ast_error(c, ch, "Generator expression must be parenthesized");
return NULL;
}
}
else if (TYPE(CHILD(ch, 0)) == STAR)
nargs++;
else
/* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */
nkeywords++;
}
}
args = _Ta3_asdl_seq_new(nargs, c->c_arena);
if (!args)
return NULL;
keywords = _Ta3_asdl_seq_new(nkeywords, c->c_arena);
if (!keywords)
return NULL;
nargs = 0; /* positional arguments + iterable argument unpackings */
nkeywords = 0; /* keyword arguments + keyword argument unpackings */
ndoublestars = 0; /* just keyword argument unpackings */
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
expr_ty e;
node *chch = CHILD(ch, 0);
if (NCH(ch) == 1) {
/* a positional argument */
if (nkeywords) {
if (ndoublestars) {
ast_error(c, chch,
"positional argument follows "
"keyword argument unpacking");
}
else {
ast_error(c, chch,
"positional argument follows "
"keyword argument");
}
return NULL;
}
e = ast_for_expr(c, chch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else if (TYPE(chch) == STAR) {
/* an iterable argument unpacking */
expr_ty starred;
if (ndoublestars) {
ast_error(c, chch,
"iterable argument unpacking follows "
"keyword argument unpacking");
return NULL;
}
e = ast_for_expr(c, CHILD(ch, 1));
if (!e)
return NULL;
starred = Starred(e, Load, LINENO(chch),
chch->n_col_offset,
c->c_arena);
if (!starred)
return NULL;
asdl_seq_SET(args, nargs++, starred);
}
else if (TYPE(chch) == DOUBLESTAR) {
/* a keyword argument unpacking */
keyword_ty kw;
i++;
e = ast_for_expr(c, CHILD(ch, 1));
if (!e)
return NULL;
kw = keyword(NULL, e, c->c_arena);
asdl_seq_SET(keywords, nkeywords++, kw);
ndoublestars++;
}
else if (TYPE(CHILD(ch, 1)) == comp_for) {
/* the lone generator expression */
e = ast_for_genexp(c, ch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else {
/* a keyword argument */
keyword_ty kw;
identifier key, tmp;
int k;
/* chch is test, but must be an identifier? */
e = ast_for_expr(c, chch);
if (!e)
return NULL;
/* f(lambda x: x[0] = 3) ends up getting parsed with
* LHS test = lambda x: x[0], and RHS test = 3.
* SF bug 132313 points out that complaining about a keyword
* then is very confusing.
*/
if (e->kind == Lambda_kind) {
ast_error(c, chch,
"lambda cannot contain assignment");
return NULL;
}
else if (e->kind != Name_kind) {
ast_error(c, chch,
"keyword can't be an expression");
return NULL;
}
else if (forbidden_name(c, e->v.Name.id, ch, 1)) {
return NULL;
}
key = e->v.Name.id;
for (k = 0; k < nkeywords; k++) {
tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg;
if (tmp && !PyUnicode_Compare(tmp, key)) {
ast_error(c, chch,
"keyword argument repeated");
return NULL;
}
}
e = ast_for_expr(c, CHILD(ch, 2));
if (!e)
return NULL;
kw = keyword(key, e, c->c_arena);
if (!kw)
return NULL;
asdl_seq_SET(keywords, nkeywords++, kw);
}
}
}
return Call(func, args, keywords, func->lineno, func->col_offset, c->c_arena);
}
static expr_ty
ast_for_testlist(struct compiling *c, const node* n)
{
/* testlist_comp: test (comp_for | (',' test)* [',']) */
/* testlist: test (',' test)* [','] */
assert(NCH(n) > 0);
if (TYPE(n) == testlist_comp) {
if (NCH(n) > 1)
assert(TYPE(CHILD(n, 1)) != comp_for);
}
else {
assert(TYPE(n) == testlist ||
TYPE(n) == testlist_star_expr);
}
if (NCH(n) == 1)
return ast_for_expr(c, CHILD(n, 0));
else {
asdl_seq *tmp = seq_for_testlist(c, n);
if (!tmp)
return NULL;
return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
static stmt_ty
ast_for_expr_stmt(struct compiling *c, const node *n)
{
int num;
REQ(n, expr_stmt);
/* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))* [TYPE_COMMENT])
annassign: ':' test ['=' test]
testlist_star_expr: (test|star_expr) (',' test|star_expr)* [',']
augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^='
| '<<=' | '>>=' | '**=' | '//='
test: ... here starts the operator precedence dance
*/
num = NCH(n);
if (num == 1 || (num == 2 && TYPE(CHILD(n, 1)) == TYPE_COMMENT)) {
expr_ty e = ast_for_testlist(c, CHILD(n, 0));
if (!e)
return NULL;
return Expr(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (TYPE(CHILD(n, 1)) == augassign) {
expr_ty expr1, expr2;
operator_ty newoperator;
node *ch = CHILD(n, 0);
expr1 = ast_for_testlist(c, ch);
if (!expr1)
return NULL;
if(!set_context(c, expr1, Store, ch))
return NULL;
/* set_context checks that most expressions are not the left side.
Augmented assignments can only have a name, a subscript, or an
attribute on the left, though, so we have to explicitly check for
those. */
switch (expr1->kind) {
case Name_kind:
case Attribute_kind:
case Subscript_kind:
break;
default:
ast_error(c, ch, "illegal expression for augmented assignment");
return NULL;
}
ch = CHILD(n, 2);
if (TYPE(ch) == testlist)
expr2 = ast_for_testlist(c, ch);
else
expr2 = ast_for_expr(c, ch);
if (!expr2)
return NULL;
newoperator = ast_for_augassign(c, CHILD(n, 1));
if (!newoperator)
return NULL;
return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (TYPE(CHILD(n, 1)) == annassign) {
expr_ty expr1, expr2, expr3;
node *ch = CHILD(n, 0);
node *deep, *ann = CHILD(n, 1);
int simple = 1;
/* AnnAssigns are only allowed in Python 3.6 or greater */
if (c->c_feature_version < 6) {
ast_error(c, ch,
"Variable annotation syntax is only supported in Python 3.6 and greater");
return NULL;
}
/* we keep track of parens to qualify (x) as expression not name */
deep = ch;
while (NCH(deep) == 1) {
deep = CHILD(deep, 0);
}
if (NCH(deep) > 0 && TYPE(CHILD(deep, 0)) == LPAR) {
simple = 0;
}
expr1 = ast_for_testlist(c, ch);
if (!expr1) {
return NULL;
}
switch (expr1->kind) {
case Name_kind:
if (forbidden_name(c, expr1->v.Name.id, n, 0)) {
return NULL;
}
expr1->v.Name.ctx = Store;
break;
case Attribute_kind:
if (forbidden_name(c, expr1->v.Attribute.attr, n, 1)) {
return NULL;
}
expr1->v.Attribute.ctx = Store;
break;
case Subscript_kind:
expr1->v.Subscript.ctx = Store;
break;
case List_kind:
ast_error(c, ch,
"only single target (not list) can be annotated");
return NULL;
case Tuple_kind:
ast_error(c, ch,
"only single target (not tuple) can be annotated");
return NULL;
default:
ast_error(c, ch,
"illegal target for annotation");
return NULL;
}
if (expr1->kind != Name_kind) {
simple = 0;
}
ch = CHILD(ann, 1);
expr2 = ast_for_expr(c, ch);
if (!expr2) {
return NULL;
}
if (NCH(ann) == 2) {
return AnnAssign(expr1, expr2, NULL, simple,
LINENO(n), n->n_col_offset, c->c_arena);
}
else {
ch = CHILD(ann, 3);
expr3 = ast_for_expr(c, ch);
if (!expr3) {
return NULL;
}
return AnnAssign(expr1, expr2, expr3, simple,
LINENO(n), n->n_col_offset, c->c_arena);
}
}
else {
int i, nch_minus_type, has_type_comment;
asdl_seq *targets;
node *value;
expr_ty expression;
string type_comment;
/* a normal assignment */
REQ(CHILD(n, 1), EQUAL);
has_type_comment = TYPE(CHILD(n, num - 1)) == TYPE_COMMENT;
nch_minus_type = num - has_type_comment;
targets = _Ta3_asdl_seq_new(nch_minus_type / 2, c->c_arena);
if (!targets)
return NULL;
for (i = 0; i < nch_minus_type - 2; i += 2) {
expr_ty e;
node *ch = CHILD(n, i);
if (TYPE(ch) == yield_expr) {
ast_error(c, ch, "assignment to yield expression not possible");
return NULL;
}
e = ast_for_testlist(c, ch);
if (!e)
return NULL;
/* set context to assign */
if (!set_context(c, e, Store, CHILD(n, i)))
return NULL;
asdl_seq_SET(targets, i / 2, e);
}
value = CHILD(n, nch_minus_type - 1);
if (TYPE(value) == testlist_star_expr)
expression = ast_for_testlist(c, value);
else
expression = ast_for_expr(c, value);
if (!expression)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, nch_minus_type));
if (!type_comment)
return NULL;
}
else
type_comment = NULL;
return Assign(targets, expression, type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}
}
static asdl_seq *
ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context)
{
asdl_seq *seq;
int i;
expr_ty e;
REQ(n, exprlist);
seq = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
if (context && !set_context(c, e, context, CHILD(n, i)))
return NULL;
}
return seq;
}
static stmt_ty
ast_for_del_stmt(struct compiling *c, const node *n)
{
asdl_seq *expr_list;
/* del_stmt: 'del' exprlist */
REQ(n, del_stmt);
expr_list = ast_for_exprlist(c, CHILD(n, 1), Del);
if (!expr_list)
return NULL;
return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_flow_stmt(struct compiling *c, const node *n)
{
/*
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
| yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
yield_expr: 'yield' testlist | 'yield' 'from' test
raise_stmt: 'raise' [test [',' test [',' test]]]
*/
node *ch;
REQ(n, flow_stmt);
ch = CHILD(n, 0);
switch (TYPE(ch)) {
case break_stmt:
return Break(LINENO(n), n->n_col_offset, c->c_arena);
case continue_stmt:
return Continue(LINENO(n), n->n_col_offset, c->c_arena);
case yield_stmt: { /* will reduce to yield_expr */
expr_ty exp = ast_for_expr(c, CHILD(ch, 0));
if (!exp)
return NULL;
return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case return_stmt:
if (NCH(ch) == 1)
return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena);
else {
expr_ty expression = ast_for_testlist(c, CHILD(ch, 1));
if (!expression)
return NULL;
return Return(expression, LINENO(n), n->n_col_offset, c->c_arena);
}
case raise_stmt:
if (NCH(ch) == 1)
return Raise(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
else if (NCH(ch) >= 2) {
expr_ty cause = NULL;
expr_ty expression = ast_for_expr(c, CHILD(ch, 1));
if (!expression)
return NULL;
if (NCH(ch) == 4) {
cause = ast_for_expr(c, CHILD(ch, 3));
if (!cause)
return NULL;
}
return Raise(expression, cause, LINENO(n), n->n_col_offset, c->c_arena);
}
/* fall through */
default:
PyErr_Format(PyExc_SystemError,
"unexpected flow_stmt: %d", TYPE(ch));
return NULL;
}
}
static alias_ty
alias_for_import_name(struct compiling *c, const node *n, int store)
{
/*
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
dotted_name: NAME ('.' NAME)*
*/
identifier str, name;
loop:
switch (TYPE(n)) {
case import_as_name: {
node *name_node = CHILD(n, 0);
str = NULL;
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
if (NCH(n) == 3) {
node *str_node = CHILD(n, 2);
str = NEW_IDENTIFIER(str_node);
if (!str)
return NULL;
if (store && forbidden_name(c, str, str_node, 0))
return NULL;
}
else {
if (forbidden_name(c, name, name_node, 0))
return NULL;
}
return alias(name, str, c->c_arena);
}
case dotted_as_name:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
node *asname_node = CHILD(n, 2);
alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0);
if (!a)
return NULL;
assert(!a->asname);
a->asname = NEW_IDENTIFIER(asname_node);
if (!a->asname)
return NULL;
if (forbidden_name(c, a->asname, asname_node, 0))
return NULL;
return a;
}
break;
case dotted_name:
if (NCH(n) == 1) {
node *name_node = CHILD(n, 0);
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
if (store && forbidden_name(c, name, name_node, 0))
return NULL;
return alias(name, NULL, c->c_arena);
}
else {
/* Create a string of the form "a.b.c" */
int i;
size_t len;
char *s;
PyObject *uni;
len = 0;
for (i = 0; i < NCH(n); i += 2)
/* length of string plus one for the dot */
len += strlen(STR(CHILD(n, i))) + 1;
len--; /* the last name doesn't have a dot */
str = PyBytes_FromStringAndSize(NULL, len);
if (!str)
return NULL;
s = PyBytes_AS_STRING(str);
if (!s)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
char *sch = STR(CHILD(n, i));
strcpy(s, STR(CHILD(n, i)));
s += strlen(sch);
*s++ = '.';
}
--s;
*s = '\0';
uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str),
PyBytes_GET_SIZE(str),
NULL);
Py_DECREF(str);
if (!uni)
return NULL;
str = uni;
PyUnicode_InternInPlace(&str);
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
}
break;
case STAR:
str = PyUnicode_InternFromString("*");
if (!str)
return NULL;
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
default:
PyErr_Format(PyExc_SystemError,
"unexpected import name: %d", TYPE(n));
return NULL;
}
PyErr_SetString(PyExc_SystemError, "unhandled import name condition");
return NULL;
}
static stmt_ty
ast_for_import_stmt(struct compiling *c, const node *n)
{
/*
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+)
'import' ('*' | '(' import_as_names ')' | import_as_names)
*/
int lineno;
int col_offset;
int i;
asdl_seq *aliases;
REQ(n, import_stmt);
lineno = LINENO(n);
col_offset = n->n_col_offset;
n = CHILD(n, 0);
if (TYPE(n) == import_name) {
n = CHILD(n, 1);
REQ(n, dotted_as_names);
aliases = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
return Import(aliases, lineno, col_offset, c->c_arena);
}
else if (TYPE(n) == import_from) {
int n_children;
int idx, ndots = 0;
alias_ty mod = NULL;
identifier modname = NULL;
/* Count the number of dots (for relative imports) and check for the
optional module name */
for (idx = 1; idx < NCH(n); idx++) {
if (TYPE(CHILD(n, idx)) == dotted_name) {
mod = alias_for_import_name(c, CHILD(n, idx), 0);
if (!mod)
return NULL;
idx++;
break;
} else if (TYPE(CHILD(n, idx)) == ELLIPSIS) {
/* three consecutive dots are tokenized as one ELLIPSIS */
ndots += 3;
continue;
} else if (TYPE(CHILD(n, idx)) != DOT) {
break;
}
ndots++;
}
idx++; /* skip over the 'import' keyword */
switch (TYPE(CHILD(n, idx))) {
case STAR:
/* from ... import * */
n = CHILD(n, idx);
n_children = 1;
break;
case LPAR:
/* from ... import (x, y, z) */
n = CHILD(n, idx + 1);
n_children = NCH(n);
break;
case import_as_names:
/* from ... import x, y, z */
n = CHILD(n, idx);
n_children = NCH(n);
if (n_children % 2 == 0) {
ast_error(c, n, "trailing comma not allowed without"
" surrounding parentheses");
return NULL;
}
break;
default:
ast_error(c, n, "Unexpected node-type in from-import");
return NULL;
}
aliases = _Ta3_asdl_seq_new((n_children + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
/* handle "from ... import *" special b/c there's no children */
if (TYPE(n) == STAR) {
alias_ty import_alias = alias_for_import_name(c, n, 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, 0, import_alias);
}
else {
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
}
if (mod != NULL)
modname = mod->name;
return ImportFrom(modname, aliases, ndots, lineno, col_offset,
c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unknown import statement: starts with command '%s'",
STR(CHILD(n, 0)));
return NULL;
}
static stmt_ty
ast_for_global_stmt(struct compiling *c, const node *n)
{
/* global_stmt: 'global' NAME (',' NAME)* */
identifier name;
asdl_seq *s;
int i;
REQ(n, global_stmt);
s = _Ta3_asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!s)
return NULL;
for (i = 1; i < NCH(n); i += 2) {
name = NEW_IDENTIFIER(CHILD(n, i));
if (!name)
return NULL;
asdl_seq_SET(s, i / 2, name);
}
return Global(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_nonlocal_stmt(struct compiling *c, const node *n)
{
/* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */
identifier name;
asdl_seq *s;
int i;
REQ(n, nonlocal_stmt);
s = _Ta3_asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!s)
return NULL;
for (i = 1; i < NCH(n); i += 2) {
name = NEW_IDENTIFIER(CHILD(n, i));
if (!name)
return NULL;
asdl_seq_SET(s, i / 2, name);
}
return Nonlocal(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_assert_stmt(struct compiling *c, const node *n)
{
/* assert_stmt: 'assert' test [',' test] */
REQ(n, assert_stmt);
if (NCH(n) == 2) {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return Assert(expression, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (NCH(n) == 4) {
expr_ty expr1, expr2;
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 3));
if (!expr2)
return NULL;
return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"improper number of parts to 'assert' statement: %d",
NCH(n));
return NULL;
}
static asdl_seq *
ast_for_suite(struct compiling *c, const node *n)
{
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
asdl_seq *seq;
stmt_ty s;
int i, total, num, end, pos = 0;
node *ch;
REQ(n, suite);
total = num_stmts(n);
seq = _Ta3_asdl_seq_new(total, c->c_arena);
if (!seq)
return NULL;
if (TYPE(CHILD(n, 0)) == simple_stmt) {
n = CHILD(n, 0);
/* simple_stmt always ends with a NEWLINE,
and may have a trailing SEMI
*/
end = NCH(n) - 1;
if (TYPE(CHILD(n, end - 1)) == SEMI)
end--;
/* loop by 2 to skip semi-colons */
for (i = 0; i < end; i += 2) {
ch = CHILD(n, i);
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
else {
i = 2;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++) {
ch = CHILD(n, i);
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
/* small_stmt or compound_stmt with only one child */
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
else {
int j;
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < NCH(ch); j += 2) {
/* statement terminates with a semi-colon ';' */
if (NCH(CHILD(ch, j)) == 0) {
assert((j + 1) == NCH(ch));
break;
}
s = ast_for_stmt(c, CHILD(ch, j));
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
}
}
assert(pos == seq->size);
return seq;
}
static stmt_ty
ast_for_if_stmt(struct compiling *c, const node *n)
{
/* if_stmt: 'if' test ':' suite ('elif' test ':' suite)*
['else' ':' suite]
*/
char *s;
REQ(n, if_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
s = STR(CHILD(n, 4));
/* s[2], the third character in the string, will be
's' for el_s_e, or
'i' for el_i_f
*/
if (s[2] == 's') {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (s[2] == 'i') {
int i, n_elif, has_else = 0;
expr_ty expression;
asdl_seq *suite_seq;
asdl_seq *orelse = NULL;
n_elif = NCH(n) - 4;
/* must reference the child n_elif+1 since 'else' token is third,
not fourth, child from the end. */
if (TYPE(CHILD(n, (n_elif + 1))) == NAME
&& STR(CHILD(n, (n_elif + 1)))[2] == 's') {
has_else = 1;
n_elif -= 3;
}
n_elif /= 4;
if (has_else) {
asdl_seq *suite_seq2;
orelse = _Ta3_asdl_seq_new(1, c->c_arena);
if (!orelse)
return NULL;
expression = ast_for_expr(c, CHILD(n, NCH(n) - 6));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4));
if (!suite_seq)
return NULL;
suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!suite_seq2)
return NULL;
asdl_seq_SET(orelse, 0,
If(expression, suite_seq, suite_seq2,
LINENO(CHILD(n, NCH(n) - 6)),
CHILD(n, NCH(n) - 6)->n_col_offset,
c->c_arena));
/* the just-created orelse handled the last elif */
n_elif--;
}
for (i = 0; i < n_elif; i++) {
int off = 5 + (n_elif - i - 1) * 4;
asdl_seq *newobj = _Ta3_asdl_seq_new(1, c->c_arena);
if (!newobj)
return NULL;
expression = ast_for_expr(c, CHILD(n, off));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, off + 2));
if (!suite_seq)
return NULL;
asdl_seq_SET(newobj, 0,
If(expression, suite_seq, orelse,
LINENO(CHILD(n, off)),
CHILD(n, off)->n_col_offset, c->c_arena));
orelse = newobj;
}
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, orelse,
LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unexpected token in 'if' statement: %s", s);
return NULL;
}
static stmt_ty
ast_for_while_stmt(struct compiling *c, const node *n)
{
/* while_stmt: 'while' test ':' suite ['else' ':' suite] */
REQ(n, while_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (NCH(n) == 7) {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of tokens for 'while' statement: %d",
NCH(n));
return NULL;
}
static stmt_ty
ast_for_for_stmt(struct compiling *c, const node *n0, bool is_async)
{
const node * const n = is_async ? CHILD(n0, 1) : n0;
asdl_seq *_target, *seq = NULL, *suite_seq;
expr_ty expression;
expr_ty target, first;
const node *node_target;
int has_type_comment;
string type_comment;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async for loops are only supported in Python 3.5 and greater");
return NULL;
}
/* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */
REQ(n, for_stmt);
has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT;
if (NCH(n) == 9 + has_type_comment) {
seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment));
if (!seq)
return NULL;
}
node_target = CHILD(n, 1);
_target = ast_for_exprlist(c, node_target, Store);
if (!_target)
return NULL;
/* Check the # of children rather than the length of _target, since
for x, in ... has 1 element in _target, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(_target, 0);
if (NCH(node_target) == 1)
target = first;
else
target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);
expression = ast_for_testlist(c, CHILD(n, 3));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment));
if (!suite_seq)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, 5));
if (!type_comment)
return NULL;
}
else
type_comment = NULL;
if (is_async)
return AsyncFor(target, expression, suite_seq, seq, type_comment,
LINENO(n0), n0->n_col_offset,
c->c_arena);
else
return For(target, expression, suite_seq, seq, type_comment,
LINENO(n), n->n_col_offset,
c->c_arena);
}
static excepthandler_ty
ast_for_except_clause(struct compiling *c, const node *exc, node *body)
{
/* except_clause: 'except' [test ['as' test]] */
REQ(exc, except_clause);
REQ(body, suite);
if (NCH(exc) == 1) {
asdl_seq *suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 2) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 4) {
asdl_seq *suite_seq;
expr_ty expression;
identifier e = NEW_IDENTIFIER(CHILD(exc, 3));
if (!e)
return NULL;
if (forbidden_name(c, e, CHILD(exc, 3), 0))
return NULL;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, e, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of children for 'except' clause: %d",
NCH(exc));
return NULL;
}
static stmt_ty
ast_for_try_stmt(struct compiling *c, const node *n)
{
const int nch = NCH(n);
int n_except = (nch - 3)/3;
asdl_seq *body, *handlers = NULL, *orelse = NULL, *finally = NULL;
REQ(n, try_stmt);
body = ast_for_suite(c, CHILD(n, 2));
if (body == NULL)
return NULL;
if (TYPE(CHILD(n, nch - 3)) == NAME) {
if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) {
if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) {
/* we can assume it's an "else",
because nch >= 9 for try-else-finally and
it would otherwise have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 4));
if (orelse == NULL)
return NULL;
n_except--;
}
finally = ast_for_suite(c, CHILD(n, nch - 1));
if (finally == NULL)
return NULL;
n_except--;
}
else {
/* we can assume it's an "else",
otherwise it would have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 1));
if (orelse == NULL)
return NULL;
n_except--;
}
}
else if (TYPE(CHILD(n, nch - 3)) != except_clause) {
ast_error(c, n, "malformed 'try' statement");
return NULL;
}
if (n_except > 0) {
int i;
/* process except statements to create a try ... except */
handlers = _Ta3_asdl_seq_new(n_except, c->c_arena);
if (handlers == NULL)
return NULL;
for (i = 0; i < n_except; i++) {
excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3),
CHILD(n, 5 + i * 3));
if (!e)
return NULL;
asdl_seq_SET(handlers, i, e);
}
}
assert(finally != NULL || asdl_seq_LEN(handlers));
return Try(body, handlers, orelse, finally, LINENO(n), n->n_col_offset, c->c_arena);
}
/* with_item: test ['as' expr] */
static withitem_ty
ast_for_with_item(struct compiling *c, const node *n)
{
expr_ty context_expr, optional_vars = NULL;
REQ(n, with_item);
context_expr = ast_for_expr(c, CHILD(n, 0));
if (!context_expr)
return NULL;
if (NCH(n) == 3) {
optional_vars = ast_for_expr(c, CHILD(n, 2));
if (!optional_vars) {
return NULL;
}
if (!set_context(c, optional_vars, Store, n)) {
return NULL;
}
}
return withitem(context_expr, optional_vars, c->c_arena);
}
/* with_stmt: 'with' with_item (',' with_item)* ':' [TYPE_COMMENT] suite */
static stmt_ty
ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async)
{
const node * const n = is_async ? CHILD(n0, 1) : n0;
int i, n_items, nch_minus_type, has_type_comment;
asdl_seq *items, *body;
string type_comment;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async with statements are only supported in Python 3.5 and greater");
return NULL;
}
REQ(n, with_stmt);
has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT;
nch_minus_type = NCH(n) - has_type_comment;
n_items = (nch_minus_type - 2) / 2;
items = _Ta3_asdl_seq_new(n_items, c->c_arena);
if (!items)
return NULL;
for (i = 1; i < nch_minus_type - 2; i += 2) {
withitem_ty item = ast_for_with_item(c, CHILD(n, i));
if (!item)
return NULL;
asdl_seq_SET(items, (i - 1) / 2, item);
}
body = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!body)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2));
if (!type_comment)
return NULL;
}
else
type_comment = NULL;
if (is_async)
return AsyncWith(items, body, type_comment, LINENO(n0), n0->n_col_offset, c->c_arena);
else
return With(items, body, type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* classdef: 'class' NAME ['(' arglist ')'] ':' suite */
PyObject *classname;
asdl_seq *s;
expr_ty call;
REQ(n, classdef);
if (NCH(n) == 4) { /* class NAME ':' suite */
s = ast_for_suite(c, CHILD(n, 3));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
if (forbidden_name(c, classname, CHILD(n, 3), 0))
return NULL;
return ClassDef(classname, NULL, NULL, s, decorator_seq,
LINENO(n), n->n_col_offset, c->c_arena);
}
if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */
s = ast_for_suite(c, CHILD(n, 5));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
if (forbidden_name(c, classname, CHILD(n, 3), 0))
return NULL;
return ClassDef(classname, NULL, NULL, s, decorator_seq,
LINENO(n), n->n_col_offset, c->c_arena);
}
/* class NAME '(' arglist ')' ':' suite */
/* build up a fake Call node so we can extract its pieces */
{
PyObject *dummy_name;
expr_ty dummy;
dummy_name = NEW_IDENTIFIER(CHILD(n, 1));
if (!dummy_name)
return NULL;
dummy = Name(dummy_name, Load, LINENO(n), n->n_col_offset, c->c_arena);
call = ast_for_call(c, CHILD(n, 3), dummy, false);
if (!call)
return NULL;
}
s = ast_for_suite(c, CHILD(n, 6));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
if (forbidden_name(c, classname, CHILD(n, 1), 0))
return NULL;
return ClassDef(classname, call->v.Call.args, call->v.Call.keywords, s,
decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_stmt(struct compiling *c, const node *n)
{
if (TYPE(n) == stmt) {
assert(NCH(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == simple_stmt) {
assert(num_stmts(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == small_stmt) {
n = CHILD(n, 0);
/* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt
| import_stmt | global_stmt | nonlocal_stmt | assert_stmt
*/
switch (TYPE(n)) {
case expr_stmt:
return ast_for_expr_stmt(c, n);
case del_stmt:
return ast_for_del_stmt(c, n);
case pass_stmt:
return Pass(LINENO(n), n->n_col_offset, c->c_arena);
case flow_stmt:
return ast_for_flow_stmt(c, n);
case import_stmt:
return ast_for_import_stmt(c, n);
case global_stmt:
return ast_for_global_stmt(c, n);
case nonlocal_stmt:
return ast_for_nonlocal_stmt(c, n);
case assert_stmt:
return ast_for_assert_stmt(c, n);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
else {
/* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
| funcdef | classdef | decorated | async_stmt
*/
node *ch = CHILD(n, 0);
REQ(n, compound_stmt);
switch (TYPE(ch)) {
case if_stmt:
return ast_for_if_stmt(c, ch);
case while_stmt:
return ast_for_while_stmt(c, ch);
case for_stmt:
return ast_for_for_stmt(c, ch, 0);
case try_stmt:
return ast_for_try_stmt(c, ch);
case with_stmt:
return ast_for_with_stmt(c, ch, 0);
case funcdef:
return ast_for_funcdef(c, ch, NULL);
case classdef:
return ast_for_classdef(c, ch, NULL);
case decorated:
return ast_for_decorated(c, ch);
case async_stmt:
return ast_for_async_stmt(c, ch);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
}
static PyObject *
parsenumber_raw(struct compiling *c, const char *s)
{
const char *end;
long x;
double dx;
Py_complex compl;
int imflag;
assert(s != NULL);
errno = 0;
end = s + strlen(s) - 1;
imflag = *end == 'j' || *end == 'J';
if (s[0] == '0') {
x = (long) PyOS_strtoul(s, (char **)&end, 0);
if (x < 0 && errno == 0) {
return PyLong_FromString(s, (char **)0, 0);
}
}
else
x = PyOS_strtol(s, (char **)&end, 0);
if (*end == '\0') {
if (errno != 0)
return PyLong_FromString(s, (char **)0, 0);
return PyLong_FromLong(x);
}
/* XXX Huge floats may silently fail */
if (imflag) {
compl.real = 0.;
compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
if (compl.imag == -1.0 && PyErr_Occurred())
return NULL;
return PyComplex_FromCComplex(compl);
}
else
{
dx = PyOS_string_to_double(s, NULL, NULL);
if (dx == -1.0 && PyErr_Occurred())
return NULL;
return PyFloat_FromDouble(dx);
}
}
static PyObject *
parsenumber(struct compiling *c, const char *s)
{
char *dup, *end;
PyObject *res = NULL;
assert(s != NULL);
if (strchr(s, '_') == NULL) {
return parsenumber_raw(c, s);
}
/* Create a duplicate without underscores. */
dup = PyMem_Malloc(strlen(s) + 1);
if (dup == NULL) {
return PyErr_NoMemory();
}
end = dup;
for (; *s; s++) {
if (*s != '_') {
*end++ = *s;
}
}
*end = '\0';
res = parsenumber_raw(c, dup);
PyMem_Free(dup);
return res;
}
static PyObject *
decode_utf8(struct compiling *c, const char **sPtr, const char *end)
{
const char *s, *t;
t = s = *sPtr;
/* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
while (s < end && (*s & 0x80)) s++;
*sPtr = s;
return PyUnicode_DecodeUTF8(t, s - t, NULL);
}
static int
warn_invalid_escape_sequence(struct compiling *c, const node *n,
unsigned char first_invalid_escape_char)
{
PyObject *msg = PyUnicode_FromFormat("invalid escape sequence \\%c",
first_invalid_escape_char);
if (msg == NULL) {
return -1;
}
if (PyErr_WarnExplicitObject(PyExc_DeprecationWarning, msg,
c->c_filename, LINENO(n),
NULL, NULL) < 0)
{
if (PyErr_ExceptionMatches(PyExc_DeprecationWarning)) {
const char *s;
/* Replace the DeprecationWarning exception with a SyntaxError
to get a more accurate error report */
PyErr_Clear();
s = PyUnicode_AsUTF8(msg);
if (s != NULL) {
ast_error(c, n, s);
}
}
Py_DECREF(msg);
return -1;
}
Py_DECREF(msg);
return 0;
}
static PyObject *
decode_unicode_with_escapes(struct compiling *c, const node *n, const char *s,
size_t len)
{
PyObject *v, *u;
char *buf;
char *p;
const char *end;
const char *first_invalid_escape;
/* check for integer overflow */
if (len > SIZE_MAX / 6)
return NULL;
/* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
"\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
u = PyBytes_FromStringAndSize((char *)NULL, len * 6);
if (u == NULL)
return NULL;
p = buf = PyBytes_AsString(u);
end = s + len;
while (s < end) {
if (*s == '\\') {
*p++ = *s++;
if (s >= end || *s & 0x80) {
strcpy(p, "u005c");
p += 5;
if (s >= end)
break;
}
}
if (*s & 0x80) { /* XXX inefficient */
PyObject *w;
int kind;
void *data;
Py_ssize_t len, i;
w = decode_utf8(c, &s, end);
if (w == NULL) {
Py_DECREF(u);
return NULL;
}
kind = PyUnicode_KIND(w);
data = PyUnicode_DATA(w);
len = PyUnicode_GET_LENGTH(w);
for (i = 0; i < len; i++) {
Py_UCS4 chr = PyUnicode_READ(kind, data, i);
sprintf(p, "\\U%08x", chr);
p += 10;
}
/* Should be impossible to overflow */
assert(p - buf <= PyBytes_GET_SIZE(u));
Py_DECREF(w);
} else {
*p++ = *s++;
}
}
len = p - buf;
s = buf;
v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape);
if (v != NULL && first_invalid_escape != NULL) {
if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) {
/* We have not decref u before because first_invalid_escape points
inside u. */
Py_XDECREF(u);
Py_DECREF(v);
return NULL;
}
}
Py_XDECREF(u);
return v;
}
static PyObject *
decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s,
size_t len)
{
const char *first_invalid_escape;
PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, 0, NULL,
&first_invalid_escape);
if (result == NULL)
return NULL;
if (first_invalid_escape != NULL) {
if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) {
Py_DECREF(result);
return NULL;
}
}
return result;
}
/* Shift locations for the given node and all its children by adding `lineno`
and `col_offset` to existing locations. */
static void fstring_shift_node_locations(node *n, int lineno, int col_offset)
{
int i;
n->n_col_offset = n->n_col_offset + col_offset;
for (i = 0; i < NCH(n); ++i) {
if (n->n_lineno && n->n_lineno < CHILD(n, i)->n_lineno) {
/* Shifting column offsets unnecessary if there's been newlines. */
col_offset = 0;
}
fstring_shift_node_locations(CHILD(n, i), lineno, col_offset);
}
n->n_lineno = n->n_lineno + lineno;
}
/* Fix locations for the given node and its children.
`parent` is the enclosing node.
`n` is the node which locations are going to be fixed relative to parent.
`expr_str` is the child node's string representation, including braces.
*/
static void
fstring_fix_node_location(const node *parent, node *n, char *expr_str)
{
char *substr = NULL;
char *start;
int lines = LINENO(parent) - 1;
int cols = parent->n_col_offset;
/* Find the full fstring to fix location information in `n`. */
while (parent && parent->n_type != STRING)
parent = parent->n_child;
if (parent && parent->n_str) {
substr = strstr(parent->n_str, expr_str);
if (substr) {
start = substr;
while (start > parent->n_str) {
if (start[0] == '\n')
break;
start--;
}
cols += substr - start;
/* Fix lineno in mulitline strings. */
while ((substr = strchr(substr + 1, '\n')))
lines--;
}
}
fstring_shift_node_locations(n, lines, cols);
}
/* Compile this expression in to an expr_ty. Add parens around the
expression, in order to allow leading spaces in the expression. */
static expr_ty
fstring_compile_expr(const char *expr_start, const char *expr_end,
struct compiling *c, const node *n)
{
PyCompilerFlags cf;
node *mod_n;
mod_ty mod;
char *str;
Py_ssize_t len;
const char *s;
int iflags = 0;
assert(expr_end >= expr_start);
assert(*(expr_start-1) == '{');
assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':');
/* If the substring is all whitespace, it's an error. We need to catch this
here, and not when we call PyParser_SimpleParseStringFlagsFilename,
because turning the expression '' in to '()' would go from being invalid
to valid. */
for (s = expr_start; s != expr_end; s++) {
char c = *s;
/* The Python parser ignores only the following whitespace
characters (\r already is converted to \n). */
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) {
break;
}
}
if (s == expr_end) {
ast_error(c, n, "f-string: empty expression not allowed");
return NULL;
}
len = expr_end - expr_start;
/* Allocate 3 extra bytes: open paren, close paren, null byte. */
str = PyMem_RawMalloc(len + 3);
if (str == NULL) {
PyErr_NoMemory();
return NULL;
}
str[0] = '(';
memcpy(str+1, expr_start, len);
str[len+1] = ')';
str[len+2] = 0;
cf.cf_flags = PyCF_ONLY_AST;
_Ta3Parser_UpdateFlags(&cf, &iflags, c->c_feature_version);
mod_n = Ta3Parser_SimpleParseStringFlagsFilename(str, "<fstring>",
Py_eval_input, iflags);
if (!mod_n) {
PyMem_RawFree(str);
return NULL;
}
/* Reuse str to find the correct column offset. */
str[0] = '{';
str[len+1] = '}';
fstring_fix_node_location(n, mod_n, str);
mod = Ta3AST_FromNode(mod_n, &cf, "<fstring>", c->c_feature_version, c->c_arena);
PyMem_RawFree(str);
Ta3Node_Free(mod_n);
if (!mod)
return NULL;
return mod->v.Expression.body;
}
/* Return -1 on error.
Return 0 if we reached the end of the literal.
Return 1 if we haven't reached the end of the literal, but we want
the caller to process the literal up to this point. Used for
doubled braces.
*/
static int
fstring_find_literal(const char **str, const char *end, int raw,
PyObject **literal, int recurse_lvl,
struct compiling *c, const node *n)
{
/* Get any literal string. It ends when we hit an un-doubled left
brace (which isn't part of a unicode name escape such as
"\N{EULER CONSTANT}"), or the end of the string. */
const char *s = *str;
const char *literal_start = s;
int result = 0;
assert(*literal == NULL);
while (s < end) {
char ch = *s++;
if (!raw && ch == '\\' && s < end) {
ch = *s++;
if (ch == 'N') {
if (s < end && *s++ == '{') {
while (s < end && *s++ != '}') {
}
continue;
}
break;
}
if (ch == '{' && warn_invalid_escape_sequence(c, n, ch) < 0) {
return -1;
}
}
if (ch == '{' || ch == '}') {
/* Check for doubled braces, but only at the top level. If
we checked at every level, then f'{0:{3}}' would fail
with the two closing braces. */
if (recurse_lvl == 0) {
if (s < end && *s == ch) {
/* We're going to tell the caller that the literal ends
here, but that they should continue scanning. But also
skip over the second brace when we resume scanning. */
*str = s + 1;
result = 1;
goto done;
}
/* Where a single '{' is the start of a new expression, a
single '}' is not allowed. */
if (ch == '}') {
*str = s - 1;
ast_error(c, n, "f-string: single '}' is not allowed");
return -1;
}
}
/* We're either at a '{', which means we're starting another
expression; or a '}', which means we're at the end of this
f-string (for a nested format_spec). */
s--;
break;
}
}
*str = s;
assert(s <= end);
assert(s == end || *s == '{' || *s == '}');
done:
if (literal_start != s) {
if (raw)
*literal = PyUnicode_DecodeUTF8Stateful(literal_start,
s - literal_start,
NULL, NULL);
else
*literal = decode_unicode_with_escapes(c, n, literal_start,
s - literal_start);
if (!*literal)
return -1;
}
return result;
}
/* Forward declaration because parsing is recursive. */
static expr_ty
fstring_parse(const char **str, const char *end, int raw, int recurse_lvl,
struct compiling *c, const node *n);
/* Parse the f-string at *str, ending at end. We know *str starts an
expression (so it must be a '{'). Returns the FormattedValue node,
which includes the expression, conversion character, and
format_spec expression.
Note that I don't do a perfect job here: I don't make sure that a
closing brace doesn't match an opening paren, for example. It
doesn't need to error on all invalid expressions, just correctly
find the end of all valid ones. Any errors inside the expression
will be caught when we parse it later. */
static int
fstring_find_expr(const char **str, const char *end, int raw, int recurse_lvl,
expr_ty *expression, struct compiling *c, const node *n)
{
/* Return -1 on error, else 0. */
const char *expr_start;
const char *expr_end;
expr_ty simple_expression;
expr_ty format_spec = NULL; /* Optional format specifier. */
int conversion = -1; /* The conversion char. -1 if not specified. */
/* 0 if we're not in a string, else the quote char we're trying to
match (single or double quote). */
char quote_char = 0;
/* If we're inside a string, 1=normal, 3=triple-quoted. */
int string_type = 0;
/* Keep track of nesting level for braces/parens/brackets in
expressions. */
Py_ssize_t nested_depth = 0;
/* Can only nest one level deep. */
if (recurse_lvl >= 2) {
ast_error(c, n, "f-string: expressions nested too deeply");
return -1;
}
/* The first char must be a left brace, or we wouldn't have gotten
here. Skip over it. */
assert(**str == '{');
*str += 1;
expr_start = *str;
for (; *str < end; (*str)++) {
char ch;
/* Loop invariants. */
assert(nested_depth >= 0);
assert(*str >= expr_start && *str < end);
if (quote_char)
assert(string_type == 1 || string_type == 3);
else
assert(string_type == 0);
ch = **str;
/* Nowhere inside an expression is a backslash allowed. */
if (ch == '\\') {
/* Error: can't include a backslash character, inside
parens or strings or not. */
ast_error(c, n, "f-string expression part "
"cannot include a backslash");
return -1;
}
if (quote_char) {
/* We're inside a string. See if we're at the end. */
/* This code needs to implement the same non-error logic
as tok_get from tokenizer.c, at the letter_quote
label. To actually share that code would be a
nightmare. But, it's unlikely to change and is small,
so duplicate it here. Note we don't need to catch all
of the errors, since they'll be caught when parsing the
expression. We just need to match the non-error
cases. Thus we can ignore \n in single-quoted strings,
for example. Or non-terminated strings. */
if (ch == quote_char) {
/* Does this match the string_type (single or triple
quoted)? */
if (string_type == 3) {
if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
/* We're at the end of a triple quoted string. */
*str += 2;
string_type = 0;
quote_char = 0;
continue;
}
} else {
/* We're at the end of a normal string. */
quote_char = 0;
string_type = 0;
continue;
}
}
} else if (ch == '\'' || ch == '"') {
/* Is this a triple quoted string? */
if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
string_type = 3;
*str += 2;
} else {
/* Start of a normal string. */
string_type = 1;
}
/* Start looking for the end of the string. */
quote_char = ch;
} else if (ch == '[' || ch == '{' || ch == '(') {
nested_depth++;
} else if (nested_depth != 0 &&
(ch == ']' || ch == '}' || ch == ')')) {
nested_depth--;
} else if (ch == '#') {
/* Error: can't include a comment character, inside parens
or not. */
ast_error(c, n, "f-string expression part cannot include '#'");
return -1;
} else if (nested_depth == 0 &&
(ch == '!' || ch == ':' || ch == '}')) {
/* First, test for the special case of "!=". Since '=' is
not an allowed conversion character, nothing is lost in
this test. */
if (ch == '!' && *str+1 < end && *(*str+1) == '=') {
/* This isn't a conversion character, just continue. */
continue;
}
/* Normal way out of this loop. */
break;
} else {
/* Just consume this char and loop around. */
}
}
expr_end = *str;
/* If we leave this loop in a string or with mismatched parens, we
don't care. We'll get a syntax error when compiling the
expression. But, we can produce a better error message, so
let's just do that.*/
if (quote_char) {
ast_error(c, n, "f-string: unterminated string");
return -1;
}
if (nested_depth) {
ast_error(c, n, "f-string: mismatched '(', '{', or '['");
return -1;
}
if (*str >= end)
goto unexpected_end_of_string;
/* Compile the expression as soon as possible, so we show errors
related to the expression before errors related to the
conversion or format_spec. */
simple_expression = fstring_compile_expr(expr_start, expr_end, c, n);
if (!simple_expression)
return -1;
/* Check for a conversion char, if present. */
if (**str == '!') {
*str += 1;
if (*str >= end)
goto unexpected_end_of_string;
conversion = **str;
*str += 1;
/* Validate the conversion. */
if (!(conversion == 's' || conversion == 'r'
|| conversion == 'a')) {
ast_error(c, n, "f-string: invalid conversion character: "
"expected 's', 'r', or 'a'");
return -1;
}
}
/* Check for the format spec, if present. */
if (*str >= end)
goto unexpected_end_of_string;
if (**str == ':') {
*str += 1;
if (*str >= end)
goto unexpected_end_of_string;
/* Parse the format spec. */
format_spec = fstring_parse(str, end, raw, recurse_lvl+1, c, n);
if (!format_spec)
return -1;
}
if (*str >= end || **str != '}')
goto unexpected_end_of_string;
/* We're at a right brace. Consume it. */
assert(*str < end);
assert(**str == '}');
*str += 1;
/* And now create the FormattedValue node that represents this
entire expression with the conversion and format spec. */
*expression = FormattedValue(simple_expression, conversion,
format_spec, LINENO(n), n->n_col_offset,
c->c_arena);
if (!*expression)
return -1;
return 0;
unexpected_end_of_string:
ast_error(c, n, "f-string: expecting '}'");
return -1;
}
/* Return -1 on error.
Return 0 if we have a literal (possible zero length) and an
expression (zero length if at the end of the string.
Return 1 if we have a literal, but no expression, and we want the
caller to call us again. This is used to deal with doubled
braces.
When called multiple times on the string 'a{{b{0}c', this function
will return:
1. the literal 'a{' with no expression, and a return value
of 1. Despite the fact that there's no expression, the return
value of 1 means we're not finished yet.
2. the literal 'b' and the expression '0', with a return value of
0. The fact that there's an expression means we're not finished.
3. literal 'c' with no expression and a return value of 0. The
combination of the return value of 0 with no expression means
we're finished.
*/
static int
fstring_find_literal_and_expr(const char **str, const char *end, int raw,
int recurse_lvl, PyObject **literal,
expr_ty *expression,
struct compiling *c, const node *n)
{
int result;
assert(*literal == NULL && *expression == NULL);
/* Get any literal string. */
result = fstring_find_literal(str, end, raw, literal, recurse_lvl, c, n);
if (result < 0)
goto error;
assert(result == 0 || result == 1);
if (result == 1)
/* We have a literal, but don't look at the expression. */
return 1;
if (*str >= end || **str == '}')
/* We're at the end of the string or the end of a nested
f-string: no expression. The top-level error case where we
expect to be at the end of the string but we're at a '}' is
handled later. */
return 0;
/* We must now be the start of an expression, on a '{'. */
assert(**str == '{');
if (fstring_find_expr(str, end, raw, recurse_lvl, expression, c, n) < 0)
goto error;
return 0;
error:
Py_CLEAR(*literal);
return -1;
}
#define EXPRLIST_N_CACHED 64
typedef struct {
/* Incrementally build an array of expr_ty, so be used in an
asdl_seq. Cache some small but reasonably sized number of
expr_ty's, and then after that start dynamically allocating,
doubling the number allocated each time. Note that the f-string
f'{0}a{1}' contains 3 expr_ty's: 2 FormattedValue's, and one
Str for the literal 'a'. So you add expr_ty's about twice as
fast as you add exressions in an f-string. */
Py_ssize_t allocated; /* Number we've allocated. */
Py_ssize_t size; /* Number we've used. */
expr_ty *p; /* Pointer to the memory we're actually
using. Will point to 'data' until we
start dynamically allocating. */
expr_ty data[EXPRLIST_N_CACHED];
} ExprList;
#ifdef NDEBUG
#define ExprList_check_invariants(l)
#else
static void
ExprList_check_invariants(ExprList *l)
{
/* Check our invariants. Make sure this object is "live", and
hasn't been deallocated. */
assert(l->size >= 0);
assert(l->p != NULL);
if (l->size <= EXPRLIST_N_CACHED)
assert(l->data == l->p);
}
#endif
static void
ExprList_Init(ExprList *l)
{
l->allocated = EXPRLIST_N_CACHED;
l->size = 0;
/* Until we start allocating dynamically, p points to data. */
l->p = l->data;
ExprList_check_invariants(l);
}
static int
ExprList_Append(ExprList *l, expr_ty exp)
{
ExprList_check_invariants(l);
if (l->size >= l->allocated) {
/* We need to alloc (or realloc) the memory. */
Py_ssize_t new_size = l->allocated * 2;
/* See if we've ever allocated anything dynamically. */
if (l->p == l->data) {
Py_ssize_t i;
/* We're still using the cached data. Switch to
alloc-ing. */
l->p = PyMem_RawMalloc(sizeof(expr_ty) * new_size);
if (!l->p)
return -1;
/* Copy the cached data into the new buffer. */
for (i = 0; i < l->size; i++)
l->p[i] = l->data[i];
} else {
/* Just realloc. */
expr_ty *tmp = PyMem_RawRealloc(l->p, sizeof(expr_ty) * new_size);
if (!tmp) {
PyMem_RawFree(l->p);
l->p = NULL;
return -1;
}
l->p = tmp;
}
l->allocated = new_size;
assert(l->allocated == 2 * l->size);
}
l->p[l->size++] = exp;
ExprList_check_invariants(l);
return 0;
}
static void
ExprList_Dealloc(ExprList *l)
{
ExprList_check_invariants(l);
/* If there's been an error, or we've never dynamically allocated,
do nothing. */
if (!l->p || l->p == l->data) {
/* Do nothing. */
} else {
/* We have dynamically allocated. Free the memory. */
PyMem_RawFree(l->p);
}
l->p = NULL;
l->size = -1;
}
static asdl_seq *
ExprList_Finish(ExprList *l, PyArena *arena)
{
asdl_seq *seq;
ExprList_check_invariants(l);
/* Allocate the asdl_seq and copy the expressions in to it. */
seq = _Ta3_asdl_seq_new(l->size, arena);
if (seq) {
Py_ssize_t i;
for (i = 0; i < l->size; i++)
asdl_seq_SET(seq, i, l->p[i]);
}
ExprList_Dealloc(l);
return seq;
}
/* The FstringParser is designed to add a mix of strings and
f-strings, and concat them together as needed. Ultimately, it
generates an expr_ty. */
typedef struct {
PyObject *last_str;
ExprList expr_list;
int fmode;
} FstringParser;
#ifdef NDEBUG
#define FstringParser_check_invariants(state)
#else
static void
FstringParser_check_invariants(FstringParser *state)
{
if (state->last_str)
assert(PyUnicode_CheckExact(state->last_str));
ExprList_check_invariants(&state->expr_list);
}
#endif
static void
FstringParser_Init(FstringParser *state)
{
state->last_str = NULL;
state->fmode = 0;
ExprList_Init(&state->expr_list);
FstringParser_check_invariants(state);
}
static void
FstringParser_Dealloc(FstringParser *state)
{
FstringParser_check_invariants(state);
Py_XDECREF(state->last_str);
ExprList_Dealloc(&state->expr_list);
}
static PyObject *
make_str_kind(const char *raw) {
/* currently Python allows up to 2 string modifiers */
char *ch, s_kind[3] = {0, 0, 0};
ch = s_kind;
while (*raw && *raw != '\'' && *raw != '"') {
*ch++ = *raw++;
}
return PyUnicode_FromString(s_kind);
}
/* Make a Str node, but decref the PyUnicode object being added. */
static expr_ty
make_str_node_and_del(PyObject **str, struct compiling *c, const node* n)
{
PyObject *s = *str;
PyObject *kind = make_str_kind(STR(CHILD(n, 0)));
if (!kind) {
return NULL;
}
*str = NULL;
assert(PyUnicode_CheckExact(s));
if (PyArena_AddPyObject(c->c_arena, s) < 0) {
Py_DECREF(s);
return NULL;
}
return Str(s, kind, LINENO(n), n->n_col_offset, c->c_arena);
}
/* Add a non-f-string (that is, a regular literal string). str is
decref'd. */
static int
FstringParser_ConcatAndDel(FstringParser *state, PyObject *str)
{
FstringParser_check_invariants(state);
assert(PyUnicode_CheckExact(str));
if (PyUnicode_GET_LENGTH(str) == 0) {
Py_DECREF(str);
return 0;
}
if (!state->last_str) {
/* We didn't have a string before, so just remember this one. */
state->last_str = str;
} else {
/* Concatenate this with the previous string. */
PyUnicode_AppendAndDel(&state->last_str, str);
if (!state->last_str)
return -1;
}
FstringParser_check_invariants(state);
return 0;
}
/* Parse an f-string. The f-string is in *str to end, with no
'f' or quotes. */
static int
FstringParser_ConcatFstring(FstringParser *state, const char **str,
const char *end, int raw, int recurse_lvl,
struct compiling *c, const node *n)
{
FstringParser_check_invariants(state);
state->fmode = 1;
/* Parse the f-string. */
while (1) {
PyObject *literal = NULL;
expr_ty expression = NULL;
/* If there's a zero length literal in front of the
expression, literal will be NULL. If we're at the end of
the f-string, expression will be NULL (unless result == 1,
see below). */
int result = fstring_find_literal_and_expr(str, end, raw, recurse_lvl,
&literal, &expression,
c, n);
if (result < 0)
return -1;
/* Add the literal, if any. */
if (!literal) {
/* Do nothing. Just leave last_str alone (and possibly
NULL). */
} else if (!state->last_str) {
/* Note that the literal can be zero length, if the
input string is "\\\n" or "\\\r", among others. */
state->last_str = literal;
literal = NULL;
} else {
/* We have a literal, concatenate it. */
assert(PyUnicode_GET_LENGTH(literal) != 0);
if (FstringParser_ConcatAndDel(state, literal) < 0)
return -1;
literal = NULL;
}
/* We've dealt with the literal now. It can't be leaked on further
errors. */
assert(literal == NULL);
/* See if we should just loop around to get the next literal
and expression, while ignoring the expression this
time. This is used for un-doubling braces, as an
optimization. */
if (result == 1)
continue;
if (!expression)
/* We're done with this f-string. */
break;
/* We know we have an expression. Convert any existing string
to a Str node. */
if (!state->last_str) {
/* Do nothing. No previous literal. */
} else {
/* Convert the existing last_str literal to a Str node. */
expr_ty str = make_str_node_and_del(&state->last_str, c, n);
if (!str || ExprList_Append(&state->expr_list, str) < 0)
return -1;
}
if (ExprList_Append(&state->expr_list, expression) < 0)
return -1;
}
/* If recurse_lvl is zero, then we must be at the end of the
string. Otherwise, we must be at a right brace. */
if (recurse_lvl == 0 && *str < end-1) {
ast_error(c, n, "f-string: unexpected end of string");
return -1;
}
if (recurse_lvl != 0 && **str != '}') {
ast_error(c, n, "f-string: expecting '}'");
return -1;
}
FstringParser_check_invariants(state);
return 0;
}
/* Convert the partial state reflected in last_str and expr_list to an
expr_ty. The expr_ty can be a Str, or a JoinedStr. */
static expr_ty
FstringParser_Finish(FstringParser *state, struct compiling *c,
const node *n)
{
asdl_seq *seq;
FstringParser_check_invariants(state);
/* If we're just a constant string with no expressions, return
that. */
if (!state->fmode) {
assert(!state->expr_list.size);
if (!state->last_str) {
/* Create a zero length string. */
state->last_str = PyUnicode_FromStringAndSize(NULL, 0);
if (!state->last_str)
goto error;
}
return make_str_node_and_del(&state->last_str, c, n);
}
/* Create a Str node out of last_str, if needed. It will be the
last node in our expression list. */
if (state->last_str) {
expr_ty str = make_str_node_and_del(&state->last_str, c, n);
if (!str || ExprList_Append(&state->expr_list, str) < 0)
goto error;
}
/* This has already been freed. */
assert(state->last_str == NULL);
seq = ExprList_Finish(&state->expr_list, c->c_arena);
if (!seq)
goto error;
return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena);
error:
FstringParser_Dealloc(state);
return NULL;
}
/* Given an f-string (with no 'f' or quotes) that's in *str and ends
at end, parse it into an expr_ty. Return NULL on error. Adjust
str to point past the parsed portion. */
static expr_ty
fstring_parse(const char **str, const char *end, int raw, int recurse_lvl,
struct compiling *c, const node *n)
{
FstringParser state;
FstringParser_Init(&state);
if (FstringParser_ConcatFstring(&state, str, end, raw, recurse_lvl,
c, n) < 0) {
FstringParser_Dealloc(&state);
return NULL;
}
return FstringParser_Finish(&state, c, n);
}
/* n is a Python string literal, including the bracketing quote
characters, and r, b, u, &/or f prefixes (if any), and embedded
escape sequences (if any). parsestr parses it, and sets *result to
decoded Python string object. If the string is an f-string, set
*fstr and *fstrlen to the unparsed string object. Return 0 if no
errors occurred.
*/
static int
parsestr(struct compiling *c, const node *n, int *bytesmode, int *rawmode,
PyObject **result, const char **fstr, Py_ssize_t *fstrlen)
{
size_t len;
const char *s = STR(n);
int quote = Py_CHARMASK(*s);
int fmode = 0;
*bytesmode = 0;
*rawmode = 0;
*result = NULL;
*fstr = NULL;
if (Py_ISALPHA(quote)) {
while (!*bytesmode || !*rawmode) {
if (quote == 'b' || quote == 'B') {
quote = *++s;
*bytesmode = 1;
}
else if (quote == 'u' || quote == 'U') {
quote = *++s;
}
else if (quote == 'r' || quote == 'R') {
quote = *++s;
*rawmode = 1;
}
else if (quote == 'f' || quote == 'F') {
quote = *++s;
fmode = 1;
}
else {
break;
}
}
}
/* fstrings are only allowed in Python 3.6 and greater */
if (fmode && c->c_feature_version < 6) {
ast_error(c, n, "Format strings are only supported in Python 3.6 and greater");
return -1;
}
if (fmode && *bytesmode) {
PyErr_BadInternalCall();
return -1;
}
if (quote != '\'' && quote != '\"') {
PyErr_BadInternalCall();
return -1;
}
/* Skip the leading quote char. */
s++;
len = strlen(s);
if (len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string to parse is too long");
return -1;
}
if (s[--len] != quote) {
/* Last quote char must match the first. */
PyErr_BadInternalCall();
return -1;
}
if (len >= 4 && s[0] == quote && s[1] == quote) {
/* A triple quoted string. We've already skipped one quote at
the start and one at the end of the string. Now skip the
two at the start. */
s += 2;
len -= 2;
/* And check that the last two match. */
if (s[--len] != quote || s[--len] != quote) {
PyErr_BadInternalCall();
return -1;
}
}
if (fmode) {
/* Just return the bytes. The caller will parse the resulting
string. */
*fstr = s;
*fstrlen = len;
return 0;
}
/* Not an f-string. */
/* Avoid invoking escape decoding routines if possible. */
*rawmode = *rawmode || strchr(s, '\\') == NULL;
if (*bytesmode) {
/* Disallow non-ASCII characters. */
const char *ch;
for (ch = s; *ch; ch++) {
if (Py_CHARMASK(*ch) >= 0x80) {
ast_error(c, n, "bytes can only contain ASCII "
"literal characters.");
return -1;
}
}
if (*rawmode)
*result = PyBytes_FromStringAndSize(s, len);
else
*result = decode_bytes_with_escapes(c, n, s, len);
} else {
if (*rawmode)
*result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL);
else
*result = decode_unicode_with_escapes(c, n, s, len);
}
return *result == NULL ? -1 : 0;
}
/* Accepts a STRING+ atom, and produces an expr_ty node. Run through
each STRING atom, and process it as needed. For bytes, just
concatenate them together, and the result will be a Bytes node. For
normal strings and f-strings, concatenate them together. The result
will be a Str node if there were no f-strings; a FormattedValue
node if there's just an f-string (with no leading or trailing
literals), or a JoinedStr node if there are multiple f-strings or
any literals involved. */
static expr_ty
parsestrplus(struct compiling *c, const node *n)
{
int bytesmode = 0;
PyObject *bytes_str = NULL;
int i;
FstringParser state;
FstringParser_Init(&state);
for (i = 0; i < NCH(n); i++) {
int this_bytesmode;
int this_rawmode;
PyObject *s;
const char *fstr;
Py_ssize_t fstrlen = -1; /* Silence a compiler warning. */
REQ(CHILD(n, i), STRING);
if (parsestr(c, CHILD(n, i), &this_bytesmode, &this_rawmode, &s,
&fstr, &fstrlen) != 0)
goto error;
/* Check that we're not mixing bytes with unicode. */
if (i != 0 && bytesmode != this_bytesmode) {
ast_error(c, n, "cannot mix bytes and nonbytes literals");
/* s is NULL if the current string part is an f-string. */
Py_XDECREF(s);
goto error;
}
bytesmode = this_bytesmode;
if (fstr != NULL) {
int result;
assert(s == NULL && !bytesmode);
/* This is an f-string. Parse and concatenate it. */
result = FstringParser_ConcatFstring(&state, &fstr, fstr+fstrlen,
this_rawmode, 0, c, n);
if (result < 0)
goto error;
} else {
/* A string or byte string. */
assert(s != NULL && fstr == NULL);
assert(bytesmode ? PyBytes_CheckExact(s) :
PyUnicode_CheckExact(s));
if (bytesmode) {
/* For bytes, concat as we go. */
if (i == 0) {
/* First time, just remember this value. */
bytes_str = s;
} else {
PyBytes_ConcatAndDel(&bytes_str, s);
if (!bytes_str)
goto error;
}
} else {
/* This is a regular string. Concatenate it. */
if (FstringParser_ConcatAndDel(&state, s) < 0)
goto error;
}
}
}
if (bytesmode) {
PyObject *kind = make_str_kind(STR(CHILD(n, 0)));
/* Just return the bytes object and we're done. */
if (PyArena_AddPyObject(c->c_arena, bytes_str) < 0) {
Py_DECREF(kind);
goto error;
}
return Bytes(bytes_str, kind, LINENO(n), n->n_col_offset, c->c_arena);
}
/* We're not a bytes string, bytes_str should never have been set. */
assert(bytes_str == NULL);
return FstringParser_Finish(&state, c, n);
error:
Py_XDECREF(bytes_str);
FstringParser_Dealloc(&state);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1283_0 |
crossvul-cpp_data_good_157_2 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Graphics Backend for drawing to ArrayBuffer
* ----------------------------------------------------------------------------
*/
#include "jswrap_arraybuffer.h"
#include "lcd_arraybuffer.h"
#include "jsvar.h"
#include "jsvariterator.h"
// returns the BIT index, so the bottom 3 bits specify the bit in the byte
unsigned int lcdGetPixelIndex_ArrayBuffer(JsGraphics *gfx, int x, int y, int pixelCount) {
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG) {
if (y&1) x = gfx->data.width - (x+pixelCount);
}
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)
return (unsigned int)(((x + (y>>3)*gfx->data.width)<<3) | (y&7));
else
return (unsigned int)((x + y*gfx->data.width)*gfx->data.bpp);
}
unsigned int lcdGetPixel_ArrayBuffer(JsGraphics *gfx, short x, short y) {
unsigned int col = 0;
JsVar *buf = (JsVar*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,1);
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, buf, idx>>3 );
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)jsvArrayBufferIteratorGetIntegerValue(&it);
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
col = ((existing>>bitIdx)&mask);
} else {
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
col |= ((unsigned int)jsvArrayBufferIteratorGetIntegerValue(&it)) << i;
jsvArrayBufferIteratorNext(&it);
}
}
jsvArrayBufferIteratorFree(&it);
return col;
}
// set pixelCount pixels starting at x,y
void lcdSetPixels_ArrayBuffer(JsGraphics *gfx, short x, short y, short pixelCount, unsigned int col) {
JsVar *buf = (JsVar*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,pixelCount);
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, buf, idx>>3 );
unsigned int whiteMask = (1U<<gfx->data.bpp)-1;
bool shortCut = (col==0 || (col&whiteMask)==whiteMask) && (!(gfx->data.flags&JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)); // simple black or white fill
while (pixelCount--) { // writing individual bits
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
if (shortCut && idx==0) {
// Basically, if we're aligned and we're filling all 0 or all 1
// then we can go really quickly and can just fill
int wholeBytes = (gfx->data.bpp*(pixelCount+1)) >> 3;
if (wholeBytes) {
char c = (char)(col?0xFF:0);
pixelCount = (short)(pixelCount+1 - (wholeBytes*8/gfx->data.bpp));
while (wholeBytes--) {
jsvArrayBufferIteratorSetByteValue(&it, c);
jsvArrayBufferIteratorNext(&it);
}
continue;
}
}
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)jsvArrayBufferIteratorGetIntegerValue(&it);
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
jsvArrayBufferIteratorSetByteValue(&it, (char)((existing&~(mask<<bitIdx)) | ((col&mask)<<bitIdx)));
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE) {
jsvArrayBufferIteratorNext(&it);
} else {
idx += gfx->data.bpp;
if (idx>=8) jsvArrayBufferIteratorNext(&it);
}
} else { // we're writing whole bytes
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
jsvArrayBufferIteratorSetByteValue(&it, (char)(col >> i));
jsvArrayBufferIteratorNext(&it);
}
}
}
jsvArrayBufferIteratorFree(&it);
}
void lcdSetPixel_ArrayBuffer(JsGraphics *gfx, short x, short y, unsigned int col) {
lcdSetPixels_ArrayBuffer(gfx, x, y, 1, col);
}
void lcdFillRect_ArrayBuffer(struct JsGraphics *gfx, short x1, short y1, short x2, short y2) {
short y;
for (y=y1;y<=y2;y++)
lcdSetPixels_ArrayBuffer(gfx, x1, y, (short)(1+x2-x1), gfx->data.fgColor);
}
#ifndef SAVE_ON_FLASH
// Faster implementation for where we have a flat memory area
unsigned int lcdGetPixel_ArrayBuffer_flat(JsGraphics *gfx, short x, short y) {
unsigned int col = 0;
unsigned char *ptr = (unsigned char*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,1);
ptr += idx>>3;
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)*ptr;
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
col = ((existing>>bitIdx)&mask);
} else {
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
col |= ((unsigned int)*ptr) << i;
ptr++;
}
}
return col;
}
// set pixelCount pixels starting at x,y
// Faster implementation for where we have a flat memory area
void lcdSetPixels_ArrayBuffer_flat(JsGraphics *gfx, short x, short y, short pixelCount, unsigned int col) {
unsigned char *ptr = (unsigned char*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,pixelCount);
ptr += idx>>3;
unsigned int whiteMask = (1U<<gfx->data.bpp)-1;
bool shortCut = (col==0 || (col&whiteMask)==whiteMask) && (!(gfx->data.flags&JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)); // simple black or white fill
while (pixelCount--) { // writing individual bits
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
if (shortCut && idx==0) {
// Basically, if we're aligned and we're filling all 0 or all 1
// then we can go really quickly and can just fill
int wholeBytes = (gfx->data.bpp*(pixelCount+1)) >> 3;
if (wholeBytes) {
char c = (char)(col?0xFF:0);
pixelCount = (short)(pixelCount+1 - (wholeBytes*8/gfx->data.bpp));
while (wholeBytes--) {
*ptr = c;
ptr++;
}
continue;
}
}
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)*ptr;
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
assert(ptr>=gfx->backendData && ptr<((char*)gfx->backendData + graphicsGetMemoryRequired(gfx)));
*ptr = (char)((existing&~(mask<<bitIdx)) | ((col&mask)<<bitIdx));
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE) {
ptr++;
} else {
idx += gfx->data.bpp;
if (idx>=8) ptr++;
}
} else { // we're writing whole bytes
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
*ptr = (char)(col >> i);
ptr++;
}
}
}
}
// Faster implementation for where we have a flat memory area
void lcdSetPixel_ArrayBuffer_flat(JsGraphics *gfx, short x, short y, unsigned int col) {
lcdSetPixels_ArrayBuffer_flat(gfx, x, y, 1, col);
}
// Faster implementation for where we have a flat memory area
void lcdFillRect_ArrayBuffer_flat(struct JsGraphics *gfx, short x1, short y1, short x2, short y2) {
short y;
for (y=y1;y<=y2;y++)
lcdSetPixels_ArrayBuffer_flat(gfx, x1, y, (short)(1+x2-x1), gfx->data.fgColor);
}
#endif // SAVE_ON_FLASH
void lcdInit_ArrayBuffer(JsGraphics *gfx) {
// create buffer
JsVar *buf = jswrap_arraybuffer_constructor(graphicsGetMemoryRequired(gfx));
jsvUnLock2(jsvAddNamedChild(gfx->graphicsVar, buf, "buffer"), buf);
}
void lcdSetCallbacks_ArrayBuffer(JsGraphics *gfx) {
JsVar *buf = jsvObjectGetChild(gfx->graphicsVar, "buffer", 0);
#ifndef SAVE_ON_FLASH
size_t len = 0;
char *dataPtr = jsvGetDataPointer(buf, &len);
#endif
jsvUnLock(buf);
#ifndef SAVE_ON_FLASH
if (dataPtr && len>=graphicsGetMemoryRequired(gfx)) {
// nice fast mode
gfx->backendData = dataPtr;
gfx->setPixel = lcdSetPixel_ArrayBuffer_flat;
gfx->getPixel = lcdGetPixel_ArrayBuffer_flat;
gfx->fillRect = lcdFillRect_ArrayBuffer_flat;
#else
if (false) {
#endif
} else if (jsvIsArrayBuffer(buf)) {
/* NOTE: This is nasty as 'buf' is not locked. HOWEVER we know that
gfx->graphicsVar IS locked, so 'buf' isn't going anywhere */
gfx->backendData = buf;
gfx->setPixel = lcdSetPixel_ArrayBuffer;
gfx->getPixel = lcdGetPixel_ArrayBuffer;
gfx->fillRect = lcdFillRect_ArrayBuffer;
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_157_2 |
crossvul-cpp_data_good_5316_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP DDDD BBBB %
% P P D D B B %
% PPPP D D BBBB %
% P D D B B %
% P DDDD BBBB %
% %
% %
% Read/Write Palm Database ImageViewer 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
% 20071202 TS * rewrote RLE decoder - old version could cause buffer overflows
% * failure of RLE decoding now thows error RLEDecoderError
% * fixed bug in RLE decoding - now all rows are decoded, not just
% the first one
% * fixed bug in reader - record offsets now handled correctly
% * fixed bug in reader - only bits 0..2 indicate compression type
% * in writer: now using image color count instead of depth
*/
/*
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/colormap-private.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/pixel-accessor.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Typedef declarations.
*/
typedef struct _PDBInfo
{
char
name[32];
short int
attributes,
version;
size_t
create_time,
modify_time,
archive_time,
modify_number,
application_info,
sort_info;
char
type[4], /* database type identifier "vIMG" */
id[4]; /* database creator identifier "View" */
size_t
seed,
next_record;
short int
number_records;
} PDBInfo;
typedef struct _PDBImage
{
char
name[32],
version;
size_t
reserved_1,
note;
short int
x_last,
y_last;
size_t
reserved_2;
short int
width,
height;
unsigned char
type;
unsigned short
x_anchor,
y_anchor;
} PDBImage;
/*
Forward declarations.
*/
static MagickBooleanType
WritePDBImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecodeImage unpacks the packed image pixels into runlength-encoded
% pixel packets.
%
% The format of the DecodeImage method is:
%
% MagickBooleanType DecodeImage(Image *image,unsigned char *pixels,
% const size_t length)
%
% A description of each parameter follows:
%
% o image: the address of a structure of type Image.
%
% o pixels: The address of a byte (8 bits) array of pixel data created by
% the decoding process.
%
% o length: Number of bytes to read into buffer 'pixels'.
%
*/
static MagickBooleanType DecodeImage(Image *image, unsigned char *pixels,
const size_t length)
{
#define RLE_MODE_NONE -1
#define RLE_MODE_COPY 0
#define RLE_MODE_RUN 1
int data = 0, count = 0;
unsigned char *p;
int mode = RLE_MODE_NONE;
for (p = pixels; p < pixels + length; p++) {
if (0 == count) {
data = ReadBlobByte( image );
if (-1 == data) return MagickFalse;
if (data > 128) {
mode = RLE_MODE_RUN;
count = data - 128 + 1;
data = ReadBlobByte( image );
if (-1 == data) return MagickFalse;
} else {
mode = RLE_MODE_COPY;
count = data + 1;
}
}
if (RLE_MODE_COPY == mode) {
data = ReadBlobByte( image );
if (-1 == data) return MagickFalse;
}
*p = (unsigned char)data;
--count;
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P D B %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPDB() returns MagickTrue if the image format type, identified by the
% magick string, is PDB.
%
% The format of the ReadPDBImage method is:
%
% MagickBooleanType IsPDB(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 IsPDB(const unsigned char *magick,const size_t length)
{
if (length < 68)
return(MagickFalse);
if (memcmp(magick+60,"vIMGView",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPDBImage() reads an Pilot 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 ReadPDBImage method is:
%
% Image *ReadPDBImage(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 *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
unsigned char
attributes,
tag[3];
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_per_pixel,
num_pad_bytes,
one,
packets;
ssize_t
count,
img_offset,
comment_offset = 0,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PDB image file.
*/
count=ReadBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
if (count != sizeof(pdb_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_info.attributes=(short) ReadBlobMSBShort(image);
pdb_info.version=(short) ReadBlobMSBShort(image);
pdb_info.create_time=ReadBlobMSBLong(image);
pdb_info.modify_time=ReadBlobMSBLong(image);
pdb_info.archive_time=ReadBlobMSBLong(image);
pdb_info.modify_number=ReadBlobMSBLong(image);
pdb_info.application_info=ReadBlobMSBLong(image);
pdb_info.sort_info=ReadBlobMSBLong(image);
(void) ReadBlob(image,4,(unsigned char *) pdb_info.type);
(void) ReadBlob(image,4,(unsigned char *) pdb_info.id);
pdb_info.seed=ReadBlobMSBLong(image);
pdb_info.next_record=ReadBlobMSBLong(image);
pdb_info.number_records=(short) ReadBlobMSBShort(image);
if ((memcmp(pdb_info.type,"vIMG",4) != 0) ||
(memcmp(pdb_info.id,"View",4) != 0))
if (pdb_info.next_record != 0)
ThrowReaderException(CoderError,"MultipleRecordListNotSupported");
/*
Read record header.
*/
img_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
(void) attributes;
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
if (pdb_info.number_records > 1)
{
comment_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
while (num_pad_bytes-- != 0)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
/*
Read image header.
*/
count=ReadBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name);
if (count != sizeof(pdb_image.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_image.version=ReadBlobByte(image);
pdb_image.type=(unsigned char) ReadBlobByte(image);
pdb_image.reserved_1=ReadBlobMSBLong(image);
pdb_image.note=ReadBlobMSBLong(image);
pdb_image.x_last=(short) ReadBlobMSBShort(image);
pdb_image.y_last=(short) ReadBlobMSBShort(image);
pdb_image.reserved_2=ReadBlobMSBLong(image);
pdb_image.x_anchor=ReadBlobMSBShort(image);
pdb_image.y_anchor=ReadBlobMSBShort(image);
pdb_image.width=(short) ReadBlobMSBShort(image);
pdb_image.height=(short) ReadBlobMSBShort(image);
/*
Initialize image structure.
*/
image->columns=(size_t) pdb_image.width;
image->rows=(size_t) pdb_image.height;
image->depth=8;
image->storage_class=PseudoClass;
bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
one=1;
if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
packets=(bits_per_pixel*image->columns+7)/8;
pixels=(unsigned char *) AcquireQuantumMemory(packets+257UL,image->rows*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
switch (pdb_image.version & 0x07)
{
case 0:
{
image->compression=NoCompression;
count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
break;
}
case 1:
{
image->compression=RLECompression;
if (!DecodeImage(image, pixels, packets * image -> rows))
ThrowReaderException( CorruptImageError, "RLEDecoderError" );
break;
}
default:
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompressionType" );
}
p=pixels;
switch (bits_per_pixel)
{
case 1:
{
int
bit;
/*
Read 1-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 2:
{
/*
Read 2-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns-3; x+=4)
{
index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
SetPixelIndex(indexes+x+1,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
SetPixelIndex(indexes+x+2,index);
index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
SetPixelIndex(indexes+x+3,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 4:
{
/*
Read 4-bit PDB image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns-1; x+=2)
{
index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
SetPixelIndex(indexes+x+1,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (pdb_info.number_records > 1)
{
char
*comment;
int
c;
register char
*p;
size_t
length;
num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read comment.
*/
c=ReadBlobByte(image);
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; c != EOF; p++)
{
if ((size_t) (p-comment+MaxTextExtent) >= length)
{
*p='\0';
length<<=1;
length+=MaxTextExtent;
comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=c;
c=ReadBlobByte(image);
}
*p='\0';
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPDBImage() adds properties for the PDB 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 RegisterPDBImage method is:
%
% size_t RegisterPDBImage(void)
%
*/
ModuleExport size_t RegisterPDBImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("PDB");
entry->decoder=(DecodeImageHandler *) ReadPDBImage;
entry->encoder=(EncodeImageHandler *) WritePDBImage;
entry->magick=(IsImageFormatHandler *) IsPDB;
entry->description=ConstantString("Palm Database ImageViewer Format");
entry->module=ConstantString("PDB");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPDBImage() removes format registrations made by the
% PDB module from the list of supported formats.
%
% The format of the UnregisterPDBImage method is:
%
% UnregisterPDBImage(void)
%
*/
ModuleExport void UnregisterPDBImage(void)
{
(void) UnregisterMagickInfo("PDB");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P D B I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePDBImage() writes an image
%
% The format of the WritePDBImage method is:
%
% MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
%
*/
static unsigned char *EncodeRLE(unsigned char *destination,
unsigned char *source,size_t literal,size_t repeat)
{
if (literal > 0)
*destination++=(unsigned char) (literal-1);
(void) CopyMagickMemory(destination,source,literal);
destination+=literal;
if (repeat > 0)
{
*destination++=(unsigned char) (0x80 | (repeat-1));
*destination++=source[literal];
}
return(destination);
}
static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image)
{
const char
*comment;
int
bits;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
QuantumInfo
*quantum_info;
register const PixelPacket
*p;
register ssize_t
x;
register unsigned char
*q;
size_t
bits_per_pixel,
literal,
packets,
packet_size,
repeat;
ssize_t
y;
unsigned char
*buffer,
*runlength,
*scanline;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
if ((image -> colors <= 2 ) ||
(GetImageType(image,&image->exception ) == BilevelType)) {
bits_per_pixel=1;
} else if (image->colors <= 4) {
bits_per_pixel=2;
} else if (image->colors <= 8) {
bits_per_pixel=3;
} else {
bits_per_pixel=4;
}
(void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info));
(void) CopyMagickString(pdb_info.name,image_info->filename,
sizeof(pdb_info.name));
pdb_info.attributes=0;
pdb_info.version=0;
pdb_info.create_time=time(NULL);
pdb_info.modify_time=pdb_info.create_time;
pdb_info.archive_time=0;
pdb_info.modify_number=0;
pdb_info.application_info=0;
pdb_info.sort_info=0;
(void) CopyMagickMemory(pdb_info.type,"vIMG",4);
(void) CopyMagickMemory(pdb_info.id,"View",4);
pdb_info.seed=0;
pdb_info.next_record=0;
comment=GetImageProperty(image,"comment");
pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);
(void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.type);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.id);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);
(void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name));
pdb_image.version=1; /* RLE Compressed */
switch (bits_per_pixel)
{
case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */
case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */
default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */
}
pdb_image.reserved_1=0;
pdb_image.note=0;
pdb_image.x_last=0;
pdb_image.y_last=0;
pdb_image.reserved_2=0;
pdb_image.x_anchor=(unsigned short) 0xffff;
pdb_image.y_anchor=(unsigned short) 0xffff;
pdb_image.width=(short) image->columns;
if (image->columns % 16)
pdb_image.width=(short) (16*(image->columns/16+1));
pdb_image.height=(short) image->rows;
packets=((bits_per_pixel*image->columns+7)/8);
runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets,
image->rows*sizeof(*runlength));
if (runlength == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
buffer=(unsigned char *) AcquireQuantumMemory(257,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
packet_size=(size_t) (image->depth > 8 ? 2: 1);
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Convert to GRAY raster scanline.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
bits=8/(int) bits_per_pixel-1; /* start at most significant bits */
literal=0;
repeat=0;
q=runlength;
buffer[0]=0x00;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
GrayQuantum,scanline,&image->exception);
for (x=0; x < (ssize_t) pdb_image.width; x++)
{
if (x < (ssize_t) image->columns)
buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>
(8-bits_per_pixel) << bits*bits_per_pixel;
bits--;
if (bits < 0)
{
if (((literal+repeat) > 0) &&
(buffer[literal+repeat] == buffer[literal+repeat-1]))
{
if (repeat == 0)
{
literal--;
repeat++;
}
repeat++;
if (0x7f < repeat)
{
q=EncodeRLE(q,buffer,literal,repeat);
literal=0;
repeat=0;
}
}
else
{
if (repeat >= 2)
literal+=repeat;
else
{
q=EncodeRLE(q,buffer,literal,repeat);
buffer[0]=buffer[literal+repeat];
literal=0;
}
literal++;
repeat=0;
if (0x7f < literal)
{
q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);
(void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);
literal-=0x80;
}
}
bits=8/(int) bits_per_pixel-1;
buffer[literal+repeat]=0x00;
}
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
q=EncodeRLE(q,buffer,literal,repeat);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
quantum_info=DestroyQuantumInfo(quantum_info);
/*
Write the Image record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8*
pdb_info.number_records));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,0);
if (pdb_info.number_records > 1)
{
/*
Write the comment record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-
runlength));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,1);
}
/*
Write the Image data.
*/
(void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *)
pdb_image.name);
(void) WriteBlobByte(image,(unsigned char) pdb_image.version);
(void) WriteBlobByte(image,pdb_image.type);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);
(void) WriteBlobMSBShort(image,pdb_image.x_anchor);
(void) WriteBlobMSBShort(image,pdb_image.y_anchor);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);
(void) WriteBlob(image,(size_t) (q-runlength),runlength);
runlength=(unsigned char *) RelinquishMagickMemory(runlength);
if (pdb_info.number_records > 1)
(void) WriteBlobString(image,comment);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5316_0 |
crossvul-cpp_data_good_2924_0 | /* -*- linux-c -*-
GTCO digitizer USB driver
TO CHECK: Is pressure done right on report 5?
Copyright (C) 2006 GTCO CalComp
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation, and that the name of GTCO-CalComp not be used in advertising
or publicity pertaining to distribution of the software without specific,
written prior permission. GTCO-CalComp makes no representations about the
suitability of this software for any purpose. It is provided "as is"
without express or implied warranty.
GTCO-CALCOMP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL GTCO-CALCOMP BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTIONS, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
GTCO CalComp, Inc.
7125 Riverwood Drive
Columbia, MD 21046
Jeremy Roberson jroberson@gtcocalcomp.com
Scott Hill shill@gtcocalcomp.com
*/
/*#define DEBUG*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <linux/bitops.h>
#include <linux/usb/input.h>
/* Version with a Major number of 2 is for kernel inclusion only. */
#define GTCO_VERSION "2.00.0006"
/* MACROS */
#define VENDOR_ID_GTCO 0x078C
#define PID_400 0x400
#define PID_401 0x401
#define PID_1000 0x1000
#define PID_1001 0x1001
#define PID_1002 0x1002
/* Max size of a single report */
#define REPORT_MAX_SIZE 10
/* Bitmask whether pen is in range */
#define MASK_INRANGE 0x20
#define MASK_BUTTON 0x01F
#define PATHLENGTH 64
/* DATA STRUCTURES */
/* Device table */
static const struct usb_device_id gtco_usbid_table[] = {
{ USB_DEVICE(VENDOR_ID_GTCO, PID_400) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_401) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1000) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1001) },
{ USB_DEVICE(VENDOR_ID_GTCO, PID_1002) },
{ }
};
MODULE_DEVICE_TABLE (usb, gtco_usbid_table);
/* Structure to hold all of our device specific stuff */
struct gtco {
struct input_dev *inputdevice; /* input device struct pointer */
struct usb_interface *intf; /* the usb interface for this device */
struct urb *urbinfo; /* urb for incoming reports */
dma_addr_t buf_dma; /* dma addr of the data buffer*/
unsigned char * buffer; /* databuffer for reports */
char usbpath[PATHLENGTH];
int openCount;
/* Information pulled from Report Descriptor */
u32 usage;
u32 min_X;
u32 max_X;
u32 min_Y;
u32 max_Y;
s8 mintilt_X;
s8 maxtilt_X;
s8 mintilt_Y;
s8 maxtilt_Y;
u32 maxpressure;
u32 minpressure;
};
/* Code for parsing the HID REPORT DESCRIPTOR */
/* From HID1.11 spec */
struct hid_descriptor
{
struct usb_descriptor_header header;
__le16 bcdHID;
u8 bCountryCode;
u8 bNumDescriptors;
u8 bDescriptorType;
__le16 wDescriptorLength;
} __attribute__ ((packed));
#define HID_DESCRIPTOR_SIZE 9
#define HID_DEVICE_TYPE 33
#define REPORT_DEVICE_TYPE 34
#define PREF_TAG(x) ((x)>>4)
#define PREF_TYPE(x) ((x>>2)&0x03)
#define PREF_SIZE(x) ((x)&0x03)
#define TYPE_MAIN 0
#define TYPE_GLOBAL 1
#define TYPE_LOCAL 2
#define TYPE_RESERVED 3
#define TAG_MAIN_INPUT 0x8
#define TAG_MAIN_OUTPUT 0x9
#define TAG_MAIN_FEATURE 0xB
#define TAG_MAIN_COL_START 0xA
#define TAG_MAIN_COL_END 0xC
#define TAG_GLOB_USAGE 0
#define TAG_GLOB_LOG_MIN 1
#define TAG_GLOB_LOG_MAX 2
#define TAG_GLOB_PHYS_MIN 3
#define TAG_GLOB_PHYS_MAX 4
#define TAG_GLOB_UNIT_EXP 5
#define TAG_GLOB_UNIT 6
#define TAG_GLOB_REPORT_SZ 7
#define TAG_GLOB_REPORT_ID 8
#define TAG_GLOB_REPORT_CNT 9
#define TAG_GLOB_PUSH 10
#define TAG_GLOB_POP 11
#define TAG_GLOB_MAX 12
#define DIGITIZER_USAGE_TIP_PRESSURE 0x30
#define DIGITIZER_USAGE_TILT_X 0x3D
#define DIGITIZER_USAGE_TILT_Y 0x3E
/*
* This is an abbreviated parser for the HID Report Descriptor. We
* know what devices we are talking to, so this is by no means meant
* to be generic. We can make some safe assumptions:
*
* - We know there are no LONG tags, all short
* - We know that we have no MAIN Feature and MAIN Output items
* - We know what the IRQ reports are supposed to look like.
*
* The main purpose of this is to use the HID report desc to figure
* out the mins and maxs of the fields in the IRQ reports. The IRQ
* reports for 400/401 change slightly if the max X is bigger than 64K.
*
*/
static void parse_hid_report_descriptor(struct gtco *device, char * report,
int length)
{
struct device *ddev = &device->intf->dev;
int x, i = 0;
/* Tag primitive vars */
__u8 prefix;
__u8 size;
__u8 tag;
__u8 type;
__u8 data = 0;
__u16 data16 = 0;
__u32 data32 = 0;
/* For parsing logic */
int inputnum = 0;
__u32 usage = 0;
/* Global Values, indexed by TAG */
__u32 globalval[TAG_GLOB_MAX];
__u32 oldval[TAG_GLOB_MAX];
/* Debug stuff */
char maintype = 'x';
char globtype[12];
int indent = 0;
char indentstr[10] = "";
dev_dbg(ddev, "======>>>>>>PARSE<<<<<<======\n");
/* Walk this report and pull out the info we need */
while (i < length) {
prefix = report[i++];
/* Determine data size and save the data in the proper variable */
size = (1U << PREF_SIZE(prefix)) >> 1;
if (i + size > length) {
dev_err(ddev,
"Not enough data (need %d, have %d)\n",
i + size, length);
break;
}
switch (size) {
case 1:
data = report[i];
break;
case 2:
data16 = get_unaligned_le16(&report[i]);
break;
case 4:
data32 = get_unaligned_le32(&report[i]);
break;
}
/* Skip size of data */
i += size;
/* What we do depends on the tag type */
tag = PREF_TAG(prefix);
type = PREF_TYPE(prefix);
switch (type) {
case TYPE_MAIN:
strcpy(globtype, "");
switch (tag) {
case TAG_MAIN_INPUT:
/*
* The INPUT MAIN tag signifies this is
* information from a report. We need to
* figure out what it is and store the
* min/max values
*/
maintype = 'I';
if (data == 2)
strcpy(globtype, "Variable");
else if (data == 3)
strcpy(globtype, "Var|Const");
dev_dbg(ddev, "::::: Saving Report: %d input #%d Max: 0x%X(%d) Min:0x%X(%d) of %d bits\n",
globalval[TAG_GLOB_REPORT_ID], inputnum,
globalval[TAG_GLOB_LOG_MAX], globalval[TAG_GLOB_LOG_MAX],
globalval[TAG_GLOB_LOG_MIN], globalval[TAG_GLOB_LOG_MIN],
globalval[TAG_GLOB_REPORT_SZ] * globalval[TAG_GLOB_REPORT_CNT]);
/*
We can assume that the first two input items
are always the X and Y coordinates. After
that, we look for everything else by
local usage value
*/
switch (inputnum) {
case 0: /* X coord */
dev_dbg(ddev, "GER: X Usage: 0x%x\n", usage);
if (device->max_X == 0) {
device->max_X = globalval[TAG_GLOB_LOG_MAX];
device->min_X = globalval[TAG_GLOB_LOG_MIN];
}
break;
case 1: /* Y coord */
dev_dbg(ddev, "GER: Y Usage: 0x%x\n", usage);
if (device->max_Y == 0) {
device->max_Y = globalval[TAG_GLOB_LOG_MAX];
device->min_Y = globalval[TAG_GLOB_LOG_MIN];
}
break;
default:
/* Tilt X */
if (usage == DIGITIZER_USAGE_TILT_X) {
if (device->maxtilt_X == 0) {
device->maxtilt_X = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_X = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Tilt Y */
if (usage == DIGITIZER_USAGE_TILT_Y) {
if (device->maxtilt_Y == 0) {
device->maxtilt_Y = globalval[TAG_GLOB_LOG_MAX];
device->mintilt_Y = globalval[TAG_GLOB_LOG_MIN];
}
}
/* Pressure */
if (usage == DIGITIZER_USAGE_TIP_PRESSURE) {
if (device->maxpressure == 0) {
device->maxpressure = globalval[TAG_GLOB_LOG_MAX];
device->minpressure = globalval[TAG_GLOB_LOG_MIN];
}
}
break;
}
inputnum++;
break;
case TAG_MAIN_OUTPUT:
maintype = 'O';
break;
case TAG_MAIN_FEATURE:
maintype = 'F';
break;
case TAG_MAIN_COL_START:
maintype = 'S';
if (data == 0) {
dev_dbg(ddev, "======>>>>>> Physical\n");
strcpy(globtype, "Physical");
} else
dev_dbg(ddev, "======>>>>>>\n");
/* Indent the debug output */
indent++;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Save global tags */
for (x = 0; x < TAG_GLOB_MAX; x++)
oldval[x] = globalval[x];
break;
case TAG_MAIN_COL_END:
dev_dbg(ddev, "<<<<<<======\n");
maintype = 'E';
indent--;
for (x = 0; x < indent; x++)
indentstr[x] = '-';
indentstr[x] = 0;
/* Copy global tags back */
for (x = 0; x < TAG_GLOB_MAX; x++)
globalval[x] = oldval[x];
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data);
break;
case 2:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data16);
break;
case 4:
dev_dbg(ddev, "%sMAINTAG:(%d) %c SIZE: %d Data: %s 0x%x\n",
indentstr, tag, maintype, size, globtype, data32);
break;
}
break;
case TYPE_GLOBAL:
switch (tag) {
case TAG_GLOB_USAGE:
/*
* First time we hit the global usage tag,
* it should tell us the type of device
*/
if (device->usage == 0)
device->usage = data;
strcpy(globtype, "USAGE");
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "LOG_MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "LOG_MAX");
break;
case TAG_GLOB_PHYS_MIN:
strcpy(globtype, "PHYS_MIN");
break;
case TAG_GLOB_PHYS_MAX:
strcpy(globtype, "PHYS_MAX");
break;
case TAG_GLOB_UNIT_EXP:
strcpy(globtype, "EXP");
break;
case TAG_GLOB_UNIT:
strcpy(globtype, "UNIT");
break;
case TAG_GLOB_REPORT_SZ:
strcpy(globtype, "REPORT_SZ");
break;
case TAG_GLOB_REPORT_ID:
strcpy(globtype, "REPORT_ID");
/* New report, restart numbering */
inputnum = 0;
break;
case TAG_GLOB_REPORT_CNT:
strcpy(globtype, "REPORT_CNT");
break;
case TAG_GLOB_PUSH:
strcpy(globtype, "PUSH");
break;
case TAG_GLOB_POP:
strcpy(globtype, "POP");
break;
}
/* Check to make sure we have a good tag number
so we don't overflow array */
if (tag < TAG_GLOB_MAX) {
switch (size) {
case 1:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data);
globalval[tag] = data;
break;
case 2:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data16);
globalval[tag] = data16;
break;
case 4:
dev_dbg(ddev, "%sGLOBALTAG:%s(%d) SIZE: %d Data: 0x%x\n",
indentstr, globtype, tag, size, data32);
globalval[tag] = data32;
break;
}
} else {
dev_dbg(ddev, "%sGLOBALTAG: ILLEGAL TAG:%d SIZE: %d\n",
indentstr, tag, size);
}
break;
case TYPE_LOCAL:
switch (tag) {
case TAG_GLOB_USAGE:
strcpy(globtype, "USAGE");
/* Always 1 byte */
usage = data;
break;
case TAG_GLOB_LOG_MIN:
strcpy(globtype, "MIN");
break;
case TAG_GLOB_LOG_MAX:
strcpy(globtype, "MAX");
break;
default:
strcpy(globtype, "UNKNOWN");
break;
}
switch (size) {
case 1:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data);
break;
case 2:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data16);
break;
case 4:
dev_dbg(ddev, "%sLOCALTAG:(%d) %s SIZE: %d Data: 0x%x\n",
indentstr, tag, globtype, size, data32);
break;
}
break;
}
}
}
/* INPUT DRIVER Routines */
/*
* Called when opening the input device. This will submit the URB to
* the usb system so we start getting reports
*/
static int gtco_input_open(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
device->urbinfo->dev = interface_to_usbdev(device->intf);
if (usb_submit_urb(device->urbinfo, GFP_KERNEL))
return -EIO;
return 0;
}
/*
* Called when closing the input device. This will unlink the URB
*/
static void gtco_input_close(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
usb_kill_urb(device->urbinfo);
}
/*
* Setup input device capabilities. Tell the input system what this
* device is capable of generating.
*
* This information is based on what is read from the HID report and
* placed in the struct gtco structure
*
*/
static void gtco_setup_caps(struct input_dev *inputdev)
{
struct gtco *device = input_get_drvdata(inputdev);
/* Which events */
inputdev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) |
BIT_MASK(EV_MSC);
/* Misc event menu block */
inputdev->mscbit[0] = BIT_MASK(MSC_SCAN) | BIT_MASK(MSC_SERIAL) |
BIT_MASK(MSC_RAW);
/* Absolute values based on HID report info */
input_set_abs_params(inputdev, ABS_X, device->min_X, device->max_X,
0, 0);
input_set_abs_params(inputdev, ABS_Y, device->min_Y, device->max_Y,
0, 0);
/* Proximity */
input_set_abs_params(inputdev, ABS_DISTANCE, 0, 1, 0, 0);
/* Tilt & pressure */
input_set_abs_params(inputdev, ABS_TILT_X, device->mintilt_X,
device->maxtilt_X, 0, 0);
input_set_abs_params(inputdev, ABS_TILT_Y, device->mintilt_Y,
device->maxtilt_Y, 0, 0);
input_set_abs_params(inputdev, ABS_PRESSURE, device->minpressure,
device->maxpressure, 0, 0);
/* Transducer */
input_set_abs_params(inputdev, ABS_MISC, 0, 0xFF, 0, 0);
}
/* USB Routines */
/*
* URB callback routine. Called when we get IRQ reports from the
* digitizer.
*
* This bridges the USB and input device worlds. It generates events
* on the input device based on the USB reports.
*/
static void gtco_urb_callback(struct urb *urbinfo)
{
struct gtco *device = urbinfo->context;
struct input_dev *inputdev;
int rc;
u32 val = 0;
char le_buffer[2];
inputdev = device->inputdevice;
/* Was callback OK? */
if (urbinfo->status == -ECONNRESET ||
urbinfo->status == -ENOENT ||
urbinfo->status == -ESHUTDOWN) {
/* Shutdown is occurring. Return and don't queue up any more */
return;
}
if (urbinfo->status != 0) {
/*
* Some unknown error. Hopefully temporary. Just go and
* requeue an URB
*/
goto resubmit;
}
/*
* Good URB, now process
*/
/* PID dependent when we interpret the report */
if (inputdev->id.product == PID_1000 ||
inputdev->id.product == PID_1001 ||
inputdev->id.product == PID_1002) {
/*
* Switch on the report ID
* Conveniently, the reports have more information, the higher
* the report number. We can just fall through the case
* statements if we start with the highest number report
*/
switch (device->buffer[0]) {
case 5:
/* Pressure is 9 bits */
val = ((u16)(device->buffer[8]) << 1);
val |= (u16)(device->buffer[7] >> 7);
input_report_abs(inputdev, ABS_PRESSURE,
device->buffer[8]);
/* Mask out the Y tilt value used for pressure */
device->buffer[7] = (u8)((device->buffer[7]) & 0x7F);
/* Fall thru */
case 4:
/* Tilt */
input_report_abs(inputdev, ABS_TILT_X,
sign_extend32(device->buffer[6], 6));
input_report_abs(inputdev, ABS_TILT_Y,
sign_extend32(device->buffer[7], 6));
/* Fall thru */
case 2:
case 3:
/* Convert buttons, only 5 bits possible */
val = (device->buffer[5]) & MASK_BUTTON;
/* We don't apply any meaning to the bitmask,
just report */
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
/* Fall thru */
case 1:
/* All reports have X and Y coords in the same place */
val = get_unaligned_le16(&device->buffer[1]);
input_report_abs(inputdev, ABS_X, val);
val = get_unaligned_le16(&device->buffer[3]);
input_report_abs(inputdev, ABS_Y, val);
/* Ditto for proximity bit */
val = device->buffer[5] & MASK_INRANGE ? 1 : 0;
input_report_abs(inputdev, ABS_DISTANCE, val);
/* Report 1 is an exception to how we handle buttons */
/* Buttons are an index, not a bitmask */
if (device->buffer[0] == 1) {
/*
* Convert buttons, 5 bit index
* Report value of index set as one,
* the rest as 0
*/
val = device->buffer[5] & MASK_BUTTON;
dev_dbg(&device->intf->dev,
"======>>>>>>REPORT 1: val 0x%X(%d)\n",
val, val);
/*
* We don't apply any meaning to the button
* index, just report it
*/
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
}
break;
case 7:
/* Menu blocks */
input_event(inputdev, EV_MSC, MSC_SCAN,
device->buffer[1]);
break;
}
}
/* Other pid class */
if (inputdev->id.product == PID_400 ||
inputdev->id.product == PID_401) {
/* Report 2 */
if (device->buffer[0] == 2) {
/* Menu blocks */
input_event(inputdev, EV_MSC, MSC_SCAN, device->buffer[1]);
}
/* Report 1 */
if (device->buffer[0] == 1) {
char buttonbyte;
/* IF X max > 64K, we still a bit from the y report */
if (device->max_X > 0x10000) {
val = (u16)(((u16)(device->buffer[2] << 8)) | (u8)device->buffer[1]);
val |= (u32)(((u8)device->buffer[3] & 0x1) << 16);
input_report_abs(inputdev, ABS_X, val);
le_buffer[0] = (u8)((u8)(device->buffer[3]) >> 1);
le_buffer[0] |= (u8)((device->buffer[3] & 0x1) << 7);
le_buffer[1] = (u8)(device->buffer[4] >> 1);
le_buffer[1] |= (u8)((device->buffer[5] & 0x1) << 7);
val = get_unaligned_le16(le_buffer);
input_report_abs(inputdev, ABS_Y, val);
/*
* Shift the button byte right by one to
* make it look like the standard report
*/
buttonbyte = device->buffer[5] >> 1;
} else {
val = get_unaligned_le16(&device->buffer[1]);
input_report_abs(inputdev, ABS_X, val);
val = get_unaligned_le16(&device->buffer[3]);
input_report_abs(inputdev, ABS_Y, val);
buttonbyte = device->buffer[5];
}
/* BUTTONS and PROXIMITY */
val = buttonbyte & MASK_INRANGE ? 1 : 0;
input_report_abs(inputdev, ABS_DISTANCE, val);
/* Convert buttons, only 4 bits possible */
val = buttonbyte & 0x0F;
#ifdef USE_BUTTONS
for (i = 0; i < 5; i++)
input_report_key(inputdev, BTN_DIGI + i, val & (1 << i));
#else
/* We don't apply any meaning to the bitmask, just report */
input_event(inputdev, EV_MSC, MSC_SERIAL, val);
#endif
/* TRANSDUCER */
input_report_abs(inputdev, ABS_MISC, device->buffer[6]);
}
}
/* Everybody gets report ID's */
input_event(inputdev, EV_MSC, MSC_RAW, device->buffer[0]);
/* Sync it up */
input_sync(inputdev);
resubmit:
rc = usb_submit_urb(urbinfo, GFP_ATOMIC);
if (rc != 0)
dev_err(&device->intf->dev,
"usb_submit_urb failed rc=0x%x\n", rc);
}
/*
* The probe routine. This is called when the kernel find the matching USB
* vendor/product. We do the following:
*
* - Allocate mem for a local structure to manage the device
* - Request a HID Report Descriptor from the device and parse it to
* find out the device parameters
* - Create an input device and assign it attributes
* - Allocate an URB so the device can talk to us when the input
* queue is open
*/
static int gtco_probe(struct usb_interface *usbinterface,
const struct usb_device_id *id)
{
struct gtco *gtco;
struct input_dev *input_dev;
struct hid_descriptor *hid_desc;
char *report;
int result = 0, retry;
int error;
struct usb_endpoint_descriptor *endpoint;
struct usb_device *udev = interface_to_usbdev(usbinterface);
/* Allocate memory for device structure */
gtco = kzalloc(sizeof(struct gtco), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gtco || !input_dev) {
dev_err(&usbinterface->dev, "No more memory\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Set pointer to the input device */
gtco->inputdevice = input_dev;
/* Save interface information */
gtco->intf = usbinterface;
/* Allocate some data for incoming reports */
gtco->buffer = usb_alloc_coherent(udev, REPORT_MAX_SIZE,
GFP_KERNEL, >co->buf_dma);
if (!gtco->buffer) {
dev_err(&usbinterface->dev, "No more memory for us buffers\n");
error = -ENOMEM;
goto err_free_devs;
}
/* Allocate URB for reports */
gtco->urbinfo = usb_alloc_urb(0, GFP_KERNEL);
if (!gtco->urbinfo) {
dev_err(&usbinterface->dev, "Failed to allocate URB\n");
error = -ENOMEM;
goto err_free_buf;
}
/* Sanity check that a device has an endpoint */
if (usbinterface->altsetting[0].desc.bNumEndpoints < 1) {
dev_err(&usbinterface->dev,
"Invalid number of endpoints\n");
error = -EINVAL;
goto err_free_urb;
}
/*
* The endpoint is always altsetting 0, we know this since we know
* this device only has one interrupt endpoint
*/
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
/* Some debug */
dev_dbg(&usbinterface->dev, "gtco # interfaces: %d\n", usbinterface->num_altsetting);
dev_dbg(&usbinterface->dev, "num endpoints: %d\n", usbinterface->cur_altsetting->desc.bNumEndpoints);
dev_dbg(&usbinterface->dev, "interface class: %d\n", usbinterface->cur_altsetting->desc.bInterfaceClass);
dev_dbg(&usbinterface->dev, "endpoint: attribute:0x%x type:0x%x\n", endpoint->bmAttributes, endpoint->bDescriptorType);
if (usb_endpoint_xfer_int(endpoint))
dev_dbg(&usbinterface->dev, "endpoint: we have interrupt endpoint\n");
dev_dbg(&usbinterface->dev, "endpoint extra len:%d\n", usbinterface->altsetting[0].extralen);
/*
* Find the HID descriptor so we can find out the size of the
* HID report descriptor
*/
if (usb_get_extra_descriptor(usbinterface->cur_altsetting,
HID_DEVICE_TYPE, &hid_desc) != 0) {
dev_err(&usbinterface->dev,
"Can't retrieve exta USB descriptor to get hid report descriptor length\n");
error = -EIO;
goto err_free_urb;
}
dev_dbg(&usbinterface->dev,
"Extra descriptor success: type:%d len:%d\n",
hid_desc->bDescriptorType, hid_desc->wDescriptorLength);
report = kzalloc(le16_to_cpu(hid_desc->wDescriptorLength), GFP_KERNEL);
if (!report) {
dev_err(&usbinterface->dev, "No more memory for report\n");
error = -ENOMEM;
goto err_free_urb;
}
/* Couple of tries to get reply */
for (retry = 0; retry < 3; retry++) {
result = usb_control_msg(udev,
usb_rcvctrlpipe(udev, 0),
USB_REQ_GET_DESCRIPTOR,
USB_RECIP_INTERFACE | USB_DIR_IN,
REPORT_DEVICE_TYPE << 8,
0, /* interface */
report,
le16_to_cpu(hid_desc->wDescriptorLength),
5000); /* 5 secs */
dev_dbg(&usbinterface->dev, "usb_control_msg result: %d\n", result);
if (result == le16_to_cpu(hid_desc->wDescriptorLength)) {
parse_hid_report_descriptor(gtco, report, result);
break;
}
}
kfree(report);
/* If we didn't get the report, fail */
if (result != le16_to_cpu(hid_desc->wDescriptorLength)) {
dev_err(&usbinterface->dev,
"Failed to get HID Report Descriptor of size: %d\n",
hid_desc->wDescriptorLength);
error = -EIO;
goto err_free_urb;
}
/* Create a device file node */
usb_make_path(udev, gtco->usbpath, sizeof(gtco->usbpath));
strlcat(gtco->usbpath, "/input0", sizeof(gtco->usbpath));
/* Set Input device functions */
input_dev->open = gtco_input_open;
input_dev->close = gtco_input_close;
/* Set input device information */
input_dev->name = "GTCO_CalComp";
input_dev->phys = gtco->usbpath;
input_set_drvdata(input_dev, gtco);
/* Now set up all the input device capabilities */
gtco_setup_caps(input_dev);
/* Set input device required ID information */
usb_to_input_id(udev, &input_dev->id);
input_dev->dev.parent = &usbinterface->dev;
/* Setup the URB, it will be posted later on open of input device */
endpoint = &usbinterface->altsetting[0].endpoint[0].desc;
usb_fill_int_urb(gtco->urbinfo,
udev,
usb_rcvintpipe(udev,
endpoint->bEndpointAddress),
gtco->buffer,
REPORT_MAX_SIZE,
gtco_urb_callback,
gtco,
endpoint->bInterval);
gtco->urbinfo->transfer_dma = gtco->buf_dma;
gtco->urbinfo->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Save gtco pointer in USB interface gtco */
usb_set_intfdata(usbinterface, gtco);
/* All done, now register the input device */
error = input_register_device(input_dev);
if (error)
goto err_free_urb;
return 0;
err_free_urb:
usb_free_urb(gtco->urbinfo);
err_free_buf:
usb_free_coherent(udev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
err_free_devs:
input_free_device(input_dev);
kfree(gtco);
return error;
}
/*
* This function is a standard USB function called when the USB device
* is disconnected. We will get rid of the URV, de-register the input
* device, and free up allocated memory
*/
static void gtco_disconnect(struct usb_interface *interface)
{
/* Grab private device ptr */
struct gtco *gtco = usb_get_intfdata(interface);
struct usb_device *udev = interface_to_usbdev(interface);
/* Now reverse all the registration stuff */
if (gtco) {
input_unregister_device(gtco->inputdevice);
usb_kill_urb(gtco->urbinfo);
usb_free_urb(gtco->urbinfo);
usb_free_coherent(udev, REPORT_MAX_SIZE,
gtco->buffer, gtco->buf_dma);
kfree(gtco);
}
dev_info(&interface->dev, "gtco driver disconnected\n");
}
/* STANDARD MODULE LOAD ROUTINES */
static struct usb_driver gtco_driverinfo_table = {
.name = "gtco",
.id_table = gtco_usbid_table,
.probe = gtco_probe,
.disconnect = gtco_disconnect,
};
module_usb_driver(gtco_driverinfo_table);
MODULE_DESCRIPTION("GTCO digitizer USB driver");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2924_0 |
crossvul-cpp_data_bad_4539_0 | /* pb_decode.c -- decode a protobuf using minimal resources
*
* 2011 Petteri Aimonen <jpa@kapsi.fi>
*/
/* Use the GCC warn_unused_result attribute to check that all return values
* are propagated correctly. On other compilers and gcc before 3.4.0 just
* ignore the annotation.
*/
#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
#define checkreturn
#else
#define checkreturn __attribute__((warn_unused_result))
#endif
#include "pb.h"
#include "pb_decode.h"
#include "pb_common.h"
/**************************************
* Declarations internal to this file *
**************************************/
static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);
static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof);
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size);
static bool checkreturn check_wire_type(pb_wire_type_t wire_type, pb_field_iter_t *field);
static bool checkreturn decode_basic_field(pb_istream_t *stream, pb_field_iter_t *field);
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field);
static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field);
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field);
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field);
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn find_extension_field(pb_field_iter_t *iter);
static bool pb_message_set_to_defaults(pb_field_iter_t *iter);
static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_dec_fixed(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_iter_t *field);
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
static bool checkreturn pb_skip_string(pb_istream_t *stream);
#ifdef PB_ENABLE_MALLOC
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);
static void initialize_pointer_field(void *pItem, pb_field_iter_t *field);
static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field);
static void pb_release_single_field(pb_field_iter_t *field);
#endif
#ifdef PB_WITHOUT_64BIT
#define pb_int64_t int32_t
#define pb_uint64_t uint32_t
#else
#define pb_int64_t int64_t
#define pb_uint64_t uint64_t
#endif
typedef struct {
uint32_t bitfield[(PB_MAX_REQUIRED_FIELDS + 31) / 32];
} pb_fields_seen_t;
/*******************************
* pb_istream_t implementation *
*******************************/
static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
{
size_t i;
const pb_byte_t *source = (const pb_byte_t*)stream->state;
stream->state = (pb_byte_t*)stream->state + count;
if (buf != NULL)
{
for (i = 0; i < count; i++)
buf[i] = source[i];
}
return true;
}
bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
{
if (count == 0)
return true;
#ifndef PB_BUFFER_ONLY
if (buf == NULL && stream->callback != buf_read)
{
/* Skip input bytes */
pb_byte_t tmp[16];
while (count > 16)
{
if (!pb_read(stream, tmp, 16))
return false;
count -= 16;
}
return pb_read(stream, tmp, count);
}
#endif
if (stream->bytes_left < count)
PB_RETURN_ERROR(stream, "end-of-stream");
#ifndef PB_BUFFER_ONLY
if (!stream->callback(stream, buf, count))
PB_RETURN_ERROR(stream, "io error");
#else
if (!buf_read(stream, buf, count))
return false;
#endif
stream->bytes_left -= count;
return true;
}
/* Read a single byte from input stream. buf may not be NULL.
* This is an optimization for the varint decoding. */
static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf)
{
if (stream->bytes_left == 0)
PB_RETURN_ERROR(stream, "end-of-stream");
#ifndef PB_BUFFER_ONLY
if (!stream->callback(stream, buf, 1))
PB_RETURN_ERROR(stream, "io error");
#else
*buf = *(const pb_byte_t*)stream->state;
stream->state = (pb_byte_t*)stream->state + 1;
#endif
stream->bytes_left--;
return true;
}
pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize)
{
pb_istream_t stream;
/* Cast away the const from buf without a compiler error. We are
* careful to use it only in a const manner in the callbacks.
*/
union {
void *state;
const void *c_state;
} state;
#ifdef PB_BUFFER_ONLY
stream.callback = NULL;
#else
stream.callback = &buf_read;
#endif
state.c_state = buf;
stream.state = state.state;
stream.bytes_left = bufsize;
#ifndef PB_NO_ERRMSG
stream.errmsg = NULL;
#endif
return stream;
}
/********************
* Helper functions *
********************/
static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof)
{
pb_byte_t byte;
uint32_t result;
if (!pb_readbyte(stream, &byte))
{
if (stream->bytes_left == 0)
{
if (eof)
{
*eof = true;
}
}
return false;
}
if ((byte & 0x80) == 0)
{
/* Quick case, 1 byte value */
result = byte;
}
else
{
/* Multibyte case */
uint_fast8_t bitpos = 7;
result = byte & 0x7F;
do
{
if (!pb_readbyte(stream, &byte))
return false;
if (bitpos >= 32)
{
/* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */
pb_byte_t sign_extension = (bitpos < 63) ? 0xFF : 0x01;
if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension))
{
PB_RETURN_ERROR(stream, "varint overflow");
}
}
else
{
result |= (uint32_t)(byte & 0x7F) << bitpos;
}
bitpos = (uint_fast8_t)(bitpos + 7);
} while (byte & 0x80);
if (bitpos == 35 && (byte & 0x70) != 0)
{
/* The last byte was at bitpos=28, so only bottom 4 bits fit. */
PB_RETURN_ERROR(stream, "varint overflow");
}
}
*dest = result;
return true;
}
bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
{
return pb_decode_varint32_eof(stream, dest, NULL);
}
#ifndef PB_WITHOUT_64BIT
bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
{
pb_byte_t byte;
uint_fast8_t bitpos = 0;
uint64_t result = 0;
do
{
if (bitpos >= 64)
PB_RETURN_ERROR(stream, "varint overflow");
if (!pb_readbyte(stream, &byte))
return false;
result |= (uint64_t)(byte & 0x7F) << bitpos;
bitpos = (uint_fast8_t)(bitpos + 7);
} while (byte & 0x80);
*dest = result;
return true;
}
#endif
bool checkreturn pb_skip_varint(pb_istream_t *stream)
{
pb_byte_t byte;
do
{
if (!pb_read(stream, &byte, 1))
return false;
} while (byte & 0x80);
return true;
}
bool checkreturn pb_skip_string(pb_istream_t *stream)
{
uint32_t length;
if (!pb_decode_varint32(stream, &length))
return false;
if ((size_t)length != length)
{
PB_RETURN_ERROR(stream, "size too large");
}
return pb_read(stream, NULL, (size_t)length);
}
bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
{
uint32_t temp;
*eof = false;
*wire_type = (pb_wire_type_t) 0;
*tag = 0;
if (!pb_decode_varint32_eof(stream, &temp, eof))
{
return false;
}
*tag = temp >> 3;
*wire_type = (pb_wire_type_t)(temp & 7);
return true;
}
bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
{
switch (wire_type)
{
case PB_WT_VARINT: return pb_skip_varint(stream);
case PB_WT_64BIT: return pb_read(stream, NULL, 8);
case PB_WT_STRING: return pb_skip_string(stream);
case PB_WT_32BIT: return pb_read(stream, NULL, 4);
default: PB_RETURN_ERROR(stream, "invalid wire_type");
}
}
/* Read a raw value to buffer, for the purpose of passing it to callback as
* a substream. Size is maximum size on call, and actual size on return.
*/
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size)
{
size_t max_size = *size;
switch (wire_type)
{
case PB_WT_VARINT:
*size = 0;
do
{
(*size)++;
if (*size > max_size)
PB_RETURN_ERROR(stream, "varint overflow");
if (!pb_read(stream, buf, 1))
return false;
} while (*buf++ & 0x80);
return true;
case PB_WT_64BIT:
*size = 8;
return pb_read(stream, buf, 8);
case PB_WT_32BIT:
*size = 4;
return pb_read(stream, buf, 4);
case PB_WT_STRING:
/* Calling read_raw_value with a PB_WT_STRING is an error.
* Explicitly handle this case and fallthrough to default to avoid
* compiler warnings.
*/
default: PB_RETURN_ERROR(stream, "invalid wire_type");
}
}
/* Decode string length from stream and return a substream with limited length.
* Remember to close the substream using pb_close_string_substream().
*/
bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
uint32_t size;
if (!pb_decode_varint32(stream, &size))
return false;
*substream = *stream;
if (substream->bytes_left < size)
PB_RETURN_ERROR(stream, "parent stream too short");
substream->bytes_left = (size_t)size;
stream->bytes_left -= (size_t)size;
return true;
}
bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
if (substream->bytes_left) {
if (!pb_read(substream, NULL, substream->bytes_left))
return false;
}
stream->state = substream->state;
#ifndef PB_NO_ERRMSG
stream->errmsg = substream->errmsg;
#endif
return true;
}
/*************************
* Decode a single field *
*************************/
static bool checkreturn check_wire_type(pb_wire_type_t wire_type, pb_field_iter_t *field)
{
switch (PB_LTYPE(field->type))
{
case PB_LTYPE_BOOL:
case PB_LTYPE_VARINT:
case PB_LTYPE_UVARINT:
case PB_LTYPE_SVARINT:
return wire_type == PB_WT_VARINT;
case PB_LTYPE_FIXED32:
return wire_type == PB_WT_32BIT;
case PB_LTYPE_FIXED64:
return wire_type == PB_WT_64BIT;
case PB_LTYPE_BYTES:
case PB_LTYPE_STRING:
case PB_LTYPE_SUBMESSAGE:
case PB_LTYPE_SUBMSG_W_CB:
case PB_LTYPE_FIXED_LENGTH_BYTES:
return wire_type == PB_WT_STRING;
default:
return false;
}
}
static bool checkreturn decode_basic_field(pb_istream_t *stream, pb_field_iter_t *field)
{
switch (PB_LTYPE(field->type))
{
case PB_LTYPE_BOOL:
return pb_dec_bool(stream, field);
case PB_LTYPE_VARINT:
case PB_LTYPE_UVARINT:
case PB_LTYPE_SVARINT:
return pb_dec_varint(stream, field);
case PB_LTYPE_FIXED32:
case PB_LTYPE_FIXED64:
return pb_dec_fixed(stream, field);
case PB_LTYPE_BYTES:
return pb_dec_bytes(stream, field);
case PB_LTYPE_STRING:
return pb_dec_string(stream, field);
case PB_LTYPE_SUBMESSAGE:
case PB_LTYPE_SUBMSG_W_CB:
return pb_dec_submessage(stream, field);
case PB_LTYPE_FIXED_LENGTH_BYTES:
return pb_dec_fixed_length_bytes(stream, field);
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)
{
switch (PB_HTYPE(field->type))
{
case PB_HTYPE_REQUIRED:
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
return decode_basic_field(stream, field);
case PB_HTYPE_OPTIONAL:
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
if (field->pSize != NULL)
*(bool*)field->pSize = true;
return decode_basic_field(stream, field);
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array */
bool status = true;
pb_istream_t substream;
pb_size_t *size = (pb_size_t*)field->pSize;
field->pData = (char*)field->pField + field->data_size * (*size);
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left > 0 && *size < field->array_size)
{
if (!decode_basic_field(&substream, field))
{
status = false;
break;
}
(*size)++;
field->pData = (char*)field->pData + field->data_size;
}
if (substream.bytes_left != 0)
PB_RETURN_ERROR(stream, "array overflow");
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
else
{
/* Repeated field */
pb_size_t *size = (pb_size_t*)field->pSize;
field->pData = (char*)field->pField + field->data_size * (*size);
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
if ((*size)++ >= field->array_size)
PB_RETURN_ERROR(stream, "array overflow");
return decode_basic_field(stream, field);
}
case PB_HTYPE_ONEOF:
*(pb_size_t*)field->pSize = field->tag;
if (PB_LTYPE_IS_SUBMSG(field->type))
{
/* We memset to zero so that any callbacks are set to NULL.
* This is because the callbacks might otherwise have values
* from some other union field.
* If callbacks are needed inside oneof field, use .proto
* option submsg_callback to have a separate callback function
* that can set the fields before submessage is decoded.
* pb_dec_submessage() will set any default values. */
memset(field->pData, 0, (size_t)field->data_size);
}
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
return decode_basic_field(stream, field);
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
#ifdef PB_ENABLE_MALLOC
/* Allocate storage for the field and store the pointer at iter->pData.
* array_size is the number of entries to reserve in an array.
* Zero size is not allowed, use pb_free() for releasing.
*/
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
{
void *ptr = *(void**)pData;
if (data_size == 0 || array_size == 0)
PB_RETURN_ERROR(stream, "invalid size");
#ifdef __AVR__
/* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284
* Realloc to size of 1 byte can cause corruption of the malloc structures.
*/
if (data_size == 1 && array_size == 1)
{
data_size = 2;
}
#endif
/* Check for multiplication overflows.
* This code avoids the costly division if the sizes are small enough.
* Multiplication is safe as long as only half of bits are set
* in either multiplicand.
*/
{
const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
if (data_size >= check_limit || array_size >= check_limit)
{
const size_t size_max = (size_t)-1;
if (size_max / array_size < data_size)
{
PB_RETURN_ERROR(stream, "size too large");
}
}
}
/* Allocate new or expand previous allocation */
/* Note: on failure the old pointer will remain in the structure,
* the message must be freed by caller also on error return. */
ptr = pb_realloc(ptr, array_size * data_size);
if (ptr == NULL)
PB_RETURN_ERROR(stream, "realloc failed");
*(void**)pData = ptr;
return true;
}
/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
static void initialize_pointer_field(void *pItem, pb_field_iter_t *field)
{
if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
PB_LTYPE(field->type) == PB_LTYPE_BYTES)
{
*(void**)pItem = NULL;
}
else if (PB_LTYPE_IS_SUBMSG(field->type))
{
/* We memset to zero so that any callbacks are set to NULL.
* Then set any default values. */
pb_field_iter_t submsg_iter;
memset(pItem, 0, field->data_size);
if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, pItem))
{
(void)pb_message_set_to_defaults(&submsg_iter);
}
}
}
#endif
static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)
{
#ifndef PB_ENABLE_MALLOC
PB_UNUSED(wire_type);
PB_UNUSED(field);
PB_RETURN_ERROR(stream, "no malloc support");
#else
switch (PB_HTYPE(field->type))
{
case PB_HTYPE_REQUIRED:
case PB_HTYPE_OPTIONAL:
case PB_HTYPE_ONEOF:
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL)
{
/* Duplicate field, have to release the old allocation first. */
/* FIXME: Does this work correctly for oneofs? */
pb_release_single_field(field);
}
if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
{
*(pb_size_t*)field->pSize = field->tag;
}
if (PB_LTYPE(field->type) == PB_LTYPE_STRING ||
PB_LTYPE(field->type) == PB_LTYPE_BYTES)
{
/* pb_dec_string and pb_dec_bytes handle allocation themselves */
field->pData = field->pField;
return decode_basic_field(stream, field);
}
else
{
if (!allocate_field(stream, field->pField, field->data_size, 1))
return false;
field->pData = *(void**)field->pField;
initialize_pointer_field(field->pData, field);
return decode_basic_field(stream, field);
}
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array, multiple items come in at once. */
bool status = true;
pb_size_t *size = (pb_size_t*)field->pSize;
size_t allocated_size = *size;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left)
{
if ((size_t)*size + 1 > allocated_size)
{
/* Allocate more storage. This tries to guess the
* number of remaining entries. Round the division
* upwards. */
allocated_size += (substream.bytes_left - 1) / field->data_size + 1;
if (!allocate_field(&substream, field->pField, field->data_size, allocated_size))
{
status = false;
break;
}
}
/* Decode the array entry */
field->pData = *(char**)field->pField + field->data_size * (*size);
initialize_pointer_field(field->pData, field);
if (!decode_basic_field(&substream, field))
{
status = false;
break;
}
if (*size == PB_SIZE_MAX)
{
#ifndef PB_NO_ERRMSG
stream->errmsg = "too many array entries";
#endif
status = false;
break;
}
(*size)++;
}
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
else
{
/* Normal repeated field, i.e. only one item at a time. */
pb_size_t *size = (pb_size_t*)field->pSize;
if (*size == PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "too many array entries");
if (!check_wire_type(wire_type, field))
PB_RETURN_ERROR(stream, "wrong wire type");
(*size)++;
if (!allocate_field(stream, field->pField, field->data_size, *size))
return false;
field->pData = *(char**)field->pField + field->data_size * (*size - 1);
initialize_pointer_field(field->pData, field);
return decode_basic_field(stream, field);
}
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
#endif
}
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)
{
if (!field->descriptor->field_callback)
return pb_skip_field(stream, wire_type);
if (wire_type == PB_WT_STRING)
{
pb_istream_t substream;
size_t prev_bytes_left;
if (!pb_make_string_substream(stream, &substream))
return false;
do
{
prev_bytes_left = substream.bytes_left;
if (!field->descriptor->field_callback(&substream, NULL, field))
PB_RETURN_ERROR(stream, "callback failed");
} while (substream.bytes_left > 0 && substream.bytes_left < prev_bytes_left);
if (!pb_close_string_substream(stream, &substream))
return false;
return true;
}
else
{
/* Copy the single scalar value to stack.
* This is required so that we can limit the stream length,
* which in turn allows to use same callback for packed and
* not-packed fields. */
pb_istream_t substream;
pb_byte_t buffer[10];
size_t size = sizeof(buffer);
if (!read_raw_value(stream, wire_type, buffer, &size))
return false;
substream = pb_istream_from_buffer(buffer, size);
return field->descriptor->field_callback(&substream, NULL, field);
}
}
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field)
{
#ifdef PB_ENABLE_MALLOC
/* When decoding an oneof field, check if there is old data that must be
* released first. */
if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
{
if (!pb_release_union_field(stream, field))
return false;
}
#endif
switch (PB_ATYPE(field->type))
{
case PB_ATYPE_STATIC:
return decode_static_field(stream, wire_type, field);
case PB_ATYPE_POINTER:
return decode_pointer_field(stream, wire_type, field);
case PB_ATYPE_CALLBACK:
return decode_callback_field(stream, wire_type, field);
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
/* Default handler for extension fields. Expects to have a pb_msgdesc_t
* pointer in the extension->type->arg field, pointing to a message with
* only one field in it. */
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
{
pb_field_iter_t iter;
if (!pb_field_iter_begin_extension(&iter, extension))
PB_RETURN_ERROR(stream, "invalid extension");
if (iter.tag != tag)
return true;
extension->found = true;
return decode_field(stream, wire_type, &iter);
}
/* Try to decode an unknown field as an extension field. Tries each extension
* decoder in turn, until one of them handles the field or loop ends. */
static bool checkreturn decode_extension(pb_istream_t *stream,
uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
size_t pos = stream->bytes_left;
while (extension != NULL && pos == stream->bytes_left)
{
bool status;
if (extension->type->decode)
status = extension->type->decode(stream, extension, tag, wire_type);
else
status = default_extension_decoder(stream, extension, tag, wire_type);
if (!status)
return false;
extension = extension->next;
}
return true;
}
/* Step through the iterator until an extension field is found or until all
* entries have been checked. There can be only one extension field per
* message. Returns false if no extension field is found. */
static bool checkreturn find_extension_field(pb_field_iter_t *iter)
{
pb_size_t start = iter->index;
do {
if (PB_LTYPE(iter->type) == PB_LTYPE_EXTENSION)
return true;
(void)pb_field_iter_next(iter);
} while (iter->index != start);
return false;
}
/* Initialize message fields to default values, recursively */
static bool pb_field_set_to_default(pb_field_iter_t *field)
{
pb_type_t type;
type = field->type;
if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
{
pb_extension_t *ext = *(pb_extension_t* const *)field->pData;
while (ext != NULL)
{
pb_field_iter_t ext_iter;
if (pb_field_iter_begin_extension(&ext_iter, ext))
{
ext->found = false;
if (!pb_message_set_to_defaults(&ext_iter))
return false;
}
ext = ext->next;
}
}
else if (PB_ATYPE(type) == PB_ATYPE_STATIC)
{
bool init_data = true;
if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && field->pSize != NULL)
{
/* Set has_field to false. Still initialize the optional field
* itself also. */
*(bool*)field->pSize = false;
}
else if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
/* REPEATED: Set array count to 0, no need to initialize contents.
ONEOF: Set which_field to 0. */
*(pb_size_t*)field->pSize = 0;
init_data = false;
}
if (init_data)
{
if (PB_LTYPE_IS_SUBMSG(field->type))
{
/* Initialize submessage to defaults */
pb_field_iter_t submsg_iter;
if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, field->pData))
{
if (!pb_message_set_to_defaults(&submsg_iter))
return false;
}
}
else
{
/* Initialize to zeros */
memset(field->pData, 0, (size_t)field->data_size);
}
}
}
else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
/* Initialize the pointer to NULL. */
*(void**)field->pField = NULL;
/* Initialize array count to 0. */
if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
*(pb_size_t*)field->pSize = 0;
}
}
else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
{
/* Don't overwrite callback */
}
return true;
}
static bool pb_message_set_to_defaults(pb_field_iter_t *iter)
{
pb_istream_t defstream = PB_ISTREAM_EMPTY;
uint32_t tag = 0;
pb_wire_type_t wire_type = PB_WT_VARINT;
bool eof;
if (iter->descriptor->default_value)
{
defstream = pb_istream_from_buffer(iter->descriptor->default_value, (size_t)-1);
if (!pb_decode_tag(&defstream, &wire_type, &tag, &eof))
return false;
}
do
{
if (!pb_field_set_to_default(iter))
return false;
if (tag != 0 && iter->tag == tag)
{
/* We have a default value for this field in the defstream */
if (!decode_field(&defstream, wire_type, iter))
return false;
if (!pb_decode_tag(&defstream, &wire_type, &tag, &eof))
return false;
if (iter->pSize)
*(bool*)iter->pSize = false;
}
} while (pb_field_iter_next(iter));
return true;
}
/*********************
* Decode all fields *
*********************/
static bool checkreturn pb_decode_inner(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct, unsigned int flags)
{
uint32_t extension_range_start = 0;
/* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed
* count field. This can only handle _one_ repeated fixed count field that
* is unpacked and unordered among other (non repeated fixed count) fields.
*/
pb_size_t fixed_count_field = PB_SIZE_MAX;
pb_size_t fixed_count_size = 0;
pb_size_t fixed_count_total_size = 0;
pb_fields_seen_t fields_seen = {{0, 0}};
const uint32_t allbits = ~(uint32_t)0;
pb_field_iter_t iter;
if (pb_field_iter_begin(&iter, fields, dest_struct))
{
if ((flags & PB_DECODE_NOINIT) == 0)
{
if (!pb_message_set_to_defaults(&iter))
PB_RETURN_ERROR(stream, "failed to set defaults");
}
}
while (stream->bytes_left)
{
uint32_t tag;
pb_wire_type_t wire_type;
bool eof;
if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
{
if (eof)
break;
else
return false;
}
if (tag == 0)
{
if (flags & PB_DECODE_NULLTERMINATED)
{
break;
}
else
{
PB_RETURN_ERROR(stream, "zero tag");
}
}
if (!pb_field_iter_find(&iter, tag) || PB_LTYPE(iter.type) == PB_LTYPE_EXTENSION)
{
/* No match found, check if it matches an extension. */
if (tag >= extension_range_start)
{
if (!find_extension_field(&iter))
extension_range_start = (uint32_t)-1;
else
extension_range_start = iter.tag;
if (tag >= extension_range_start)
{
size_t pos = stream->bytes_left;
if (!decode_extension(stream, tag, wire_type, &iter))
return false;
if (pos != stream->bytes_left)
{
/* The field was handled */
continue;
}
}
}
/* No match found, skip data */
if (!pb_skip_field(stream, wire_type))
return false;
continue;
}
/* If a repeated fixed count field was found, get size from
* 'fixed_count_field' as there is no counter contained in the struct.
*/
if (PB_HTYPE(iter.type) == PB_HTYPE_REPEATED && iter.pSize == &iter.array_size)
{
if (fixed_count_field != iter.index) {
/* If the new fixed count field does not match the previous one,
* check that the previous one is NULL or that it finished
* receiving all the expected data.
*/
if (fixed_count_field != PB_SIZE_MAX &&
fixed_count_size != fixed_count_total_size)
{
PB_RETURN_ERROR(stream, "wrong size for fixed count field");
}
fixed_count_field = iter.index;
fixed_count_size = 0;
fixed_count_total_size = iter.array_size;
}
iter.pSize = &fixed_count_size;
}
if (PB_HTYPE(iter.type) == PB_HTYPE_REQUIRED
&& iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
{
uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31));
fields_seen.bitfield[iter.required_field_index >> 5] |= tmp;
}
if (!decode_field(stream, wire_type, &iter))
return false;
}
/* Check that all elements of the last decoded fixed count field were present. */
if (fixed_count_field != PB_SIZE_MAX &&
fixed_count_size != fixed_count_total_size)
{
PB_RETURN_ERROR(stream, "wrong size for fixed count field");
}
/* Check that all required fields were present. */
{
/* First figure out the number of required fields by
* seeking to the end of the field array. Usually we
* are already close to end after decoding.
*/
pb_size_t req_field_count;
pb_type_t last_type;
pb_size_t i;
do {
req_field_count = iter.required_field_index;
last_type = iter.type;
} while (pb_field_iter_next(&iter));
/* Fixup if last field was also required. */
if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.tag != 0)
req_field_count++;
if (req_field_count > PB_MAX_REQUIRED_FIELDS)
req_field_count = PB_MAX_REQUIRED_FIELDS;
if (req_field_count > 0)
{
/* Check the whole words */
for (i = 0; i < (req_field_count >> 5); i++)
{
if (fields_seen.bitfield[i] != allbits)
PB_RETURN_ERROR(stream, "missing required field");
}
/* Check the remaining bits (if any) */
if ((req_field_count & 31) != 0)
{
if (fields_seen.bitfield[req_field_count >> 5] !=
(allbits >> (uint_least8_t)(32 - (req_field_count & 31))))
{
PB_RETURN_ERROR(stream, "missing required field");
}
}
}
}
return true;
}
bool checkreturn pb_decode_ex(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct, unsigned int flags)
{
bool status;
if ((flags & PB_DECODE_DELIMITED) == 0)
{
status = pb_decode_inner(stream, fields, dest_struct, flags);
}
else
{
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
status = pb_decode_inner(&substream, fields, dest_struct, flags);
if (!pb_close_string_substream(stream, &substream))
return false;
}
#ifdef PB_ENABLE_MALLOC
if (!status)
pb_release(fields, dest_struct);
#endif
return status;
}
bool checkreturn pb_decode(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct)
{
bool status;
status = pb_decode_inner(stream, fields, dest_struct, 0);
#ifdef PB_ENABLE_MALLOC
if (!status)
pb_release(fields, dest_struct);
#endif
return status;
}
#ifdef PB_ENABLE_MALLOC
/* Given an oneof field, if there has already been a field inside this oneof,
* release it before overwriting with a different one. */
static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field)
{
pb_field_iter_t old_field = *field;
pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */
pb_size_t new_tag = field->tag; /* New which_ value */
if (old_tag == 0)
return true; /* Ok, no old data in union */
if (old_tag == new_tag)
return true; /* Ok, old data is of same type => merge */
/* Release old data. The find can fail if the message struct contains
* invalid data. */
if (!pb_field_iter_find(&old_field, old_tag))
PB_RETURN_ERROR(stream, "invalid union tag");
pb_release_single_field(&old_field);
return true;
}
static void pb_release_single_field(pb_field_iter_t *field)
{
pb_type_t type;
type = field->type;
if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
{
if (*(pb_size_t*)field->pSize != field->tag)
return; /* This is not the current field in the union */
}
/* Release anything contained inside an extension or submsg.
* This has to be done even if the submsg itself is statically
* allocated. */
if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
{
/* Release fields from all extensions in the linked list */
pb_extension_t *ext = *(pb_extension_t**)field->pData;
while (ext != NULL)
{
pb_field_iter_t ext_iter;
if (pb_field_iter_begin_extension(&ext_iter, ext))
{
pb_release_single_field(&ext_iter);
}
ext = ext->next;
}
}
else if (PB_LTYPE_IS_SUBMSG(type) && PB_ATYPE(type) != PB_ATYPE_CALLBACK)
{
/* Release fields in submessage or submsg array */
pb_size_t count = 1;
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
field->pData = *(void**)field->pField;
}
else
{
field->pData = field->pField;
}
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
count = *(pb_size_t*)field->pSize;
if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > field->array_size)
{
/* Protect against corrupted _count fields */
count = field->array_size;
}
}
if (field->pData)
{
while (count--)
{
pb_release(field->submsg_desc, field->pData);
field->pData = (char*)field->pData + field->data_size;
}
}
}
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
(PB_LTYPE(type) == PB_LTYPE_STRING ||
PB_LTYPE(type) == PB_LTYPE_BYTES))
{
/* Release entries in repeated string or bytes array */
void **pItem = *(void***)field->pField;
pb_size_t count = *(pb_size_t*)field->pSize;
while (count--)
{
pb_free(*pItem);
*pItem++ = NULL;
}
}
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
/* We are going to release the array, so set the size to 0 */
*(pb_size_t*)field->pSize = 0;
}
/* Release main pointer */
pb_free(*(void**)field->pField);
*(void**)field->pField = NULL;
}
}
void pb_release(const pb_msgdesc_t *fields, void *dest_struct)
{
pb_field_iter_t iter;
if (!dest_struct)
return; /* Ignore NULL pointers, similar to free() */
if (!pb_field_iter_begin(&iter, fields, dest_struct))
return; /* Empty message type */
do
{
pb_release_single_field(&iter);
} while (pb_field_iter_next(&iter));
}
#endif
/* Field decoders */
bool pb_decode_bool(pb_istream_t *stream, bool *dest)
{
uint32_t value;
if (!pb_decode_varint32(stream, &value))
return false;
*(bool*)dest = (value != 0);
return true;
}
bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest)
{
pb_uint64_t value;
if (!pb_decode_varint(stream, &value))
return false;
if (value & 1)
*dest = (pb_int64_t)(~(value >> 1));
else
*dest = (pb_int64_t)(value >> 1);
return true;
}
bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
{
union {
uint32_t fixed32;
pb_byte_t bytes[4];
} u;
if (!pb_read(stream, u.bytes, 4))
return false;
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN && CHAR_BIT == 8
/* fast path - if we know that we're on little endian, assign directly */
*(uint32_t*)dest = u.fixed32;
#else
*(uint32_t*)dest = ((uint32_t)u.bytes[0] << 0) |
((uint32_t)u.bytes[1] << 8) |
((uint32_t)u.bytes[2] << 16) |
((uint32_t)u.bytes[3] << 24);
#endif
return true;
}
#ifndef PB_WITHOUT_64BIT
bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
{
union {
uint64_t fixed64;
pb_byte_t bytes[8];
} u;
if (!pb_read(stream, u.bytes, 8))
return false;
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN && CHAR_BIT == 8
/* fast path - if we know that we're on little endian, assign directly */
*(uint64_t*)dest = u.fixed64;
#else
*(uint64_t*)dest = ((uint64_t)u.bytes[0] << 0) |
((uint64_t)u.bytes[1] << 8) |
((uint64_t)u.bytes[2] << 16) |
((uint64_t)u.bytes[3] << 24) |
((uint64_t)u.bytes[4] << 32) |
((uint64_t)u.bytes[5] << 40) |
((uint64_t)u.bytes[6] << 48) |
((uint64_t)u.bytes[7] << 56);
#endif
return true;
}
#endif
static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_iter_t *field)
{
return pb_decode_bool(stream, (bool*)field->pData);
}
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_iter_t *field)
{
if (PB_LTYPE(field->type) == PB_LTYPE_UVARINT)
{
pb_uint64_t value, clamped;
if (!pb_decode_varint(stream, &value))
return false;
/* Cast to the proper field size, while checking for overflows */
if (field->data_size == sizeof(pb_uint64_t))
clamped = *(pb_uint64_t*)field->pData = value;
else if (field->data_size == sizeof(uint32_t))
clamped = *(uint32_t*)field->pData = (uint32_t)value;
else if (field->data_size == sizeof(uint_least16_t))
clamped = *(uint_least16_t*)field->pData = (uint_least16_t)value;
else if (field->data_size == sizeof(uint_least8_t))
clamped = *(uint_least8_t*)field->pData = (uint_least8_t)value;
else
PB_RETURN_ERROR(stream, "invalid data_size");
if (clamped != value)
PB_RETURN_ERROR(stream, "integer too large");
return true;
}
else
{
pb_uint64_t value;
pb_int64_t svalue;
pb_int64_t clamped;
if (PB_LTYPE(field->type) == PB_LTYPE_SVARINT)
{
if (!pb_decode_svarint(stream, &svalue))
return false;
}
else
{
if (!pb_decode_varint(stream, &value))
return false;
/* See issue 97: Google's C++ protobuf allows negative varint values to
* be cast as int32_t, instead of the int64_t that should be used when
* encoding. Previous nanopb versions had a bug in encoding. In order to
* not break decoding of such messages, we cast <=32 bit fields to
* int32_t first to get the sign correct.
*/
if (field->data_size == sizeof(pb_int64_t))
svalue = (pb_int64_t)value;
else
svalue = (int32_t)value;
}
/* Cast to the proper field size, while checking for overflows */
if (field->data_size == sizeof(pb_int64_t))
clamped = *(pb_int64_t*)field->pData = svalue;
else if (field->data_size == sizeof(int32_t))
clamped = *(int32_t*)field->pData = (int32_t)svalue;
else if (field->data_size == sizeof(int_least16_t))
clamped = *(int_least16_t*)field->pData = (int_least16_t)svalue;
else if (field->data_size == sizeof(int_least8_t))
clamped = *(int_least8_t*)field->pData = (int_least8_t)svalue;
else
PB_RETURN_ERROR(stream, "invalid data_size");
if (clamped != svalue)
PB_RETURN_ERROR(stream, "integer too large");
return true;
}
}
static bool checkreturn pb_dec_fixed(pb_istream_t *stream, const pb_field_iter_t *field)
{
#ifdef PB_CONVERT_DOUBLE_FLOAT
if (field->data_size == sizeof(float) && PB_LTYPE(field->type) == PB_LTYPE_FIXED64)
{
return pb_decode_double_as_float(stream, (float*)field->pData);
}
#endif
if (field->data_size == sizeof(uint32_t))
{
return pb_decode_fixed32(stream, field->pData);
}
#ifndef PB_WITHOUT_64BIT
else if (field->data_size == sizeof(uint64_t))
{
return pb_decode_fixed64(stream, field->pData);
}
#endif
else
{
PB_RETURN_ERROR(stream, "invalid data_size");
}
}
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_iter_t *field)
{
uint32_t size;
size_t alloc_size;
pb_bytes_array_t *dest;
if (!pb_decode_varint32(stream, &size))
return false;
if (size > PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "bytes overflow");
alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
if (size > alloc_size)
PB_RETURN_ERROR(stream, "size too large");
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
#ifndef PB_ENABLE_MALLOC
PB_RETURN_ERROR(stream, "no malloc support");
#else
if (stream->bytes_left < size)
PB_RETURN_ERROR(stream, "end-of-stream");
if (!allocate_field(stream, field->pData, alloc_size, 1))
return false;
dest = *(pb_bytes_array_t**)field->pData;
#endif
}
else
{
if (alloc_size > field->data_size)
PB_RETURN_ERROR(stream, "bytes overflow");
dest = (pb_bytes_array_t*)field->pData;
}
dest->size = (pb_size_t)size;
return pb_read(stream, dest->bytes, (size_t)size);
}
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_iter_t *field)
{
uint32_t size;
size_t alloc_size;
pb_byte_t *dest = (pb_byte_t*)field->pData;
if (!pb_decode_varint32(stream, &size))
return false;
if (size == (uint32_t)-1)
PB_RETURN_ERROR(stream, "size too large");
/* Space for null terminator */
alloc_size = (size_t)(size + 1);
if (alloc_size < size)
PB_RETURN_ERROR(stream, "size too large");
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
#ifndef PB_ENABLE_MALLOC
PB_RETURN_ERROR(stream, "no malloc support");
#else
if (stream->bytes_left < size)
PB_RETURN_ERROR(stream, "end-of-stream");
if (!allocate_field(stream, field->pData, alloc_size, 1))
return false;
dest = *(pb_byte_t**)field->pData;
#endif
}
else
{
if (alloc_size > field->data_size)
PB_RETURN_ERROR(stream, "string overflow");
}
dest[size] = 0;
if (!pb_read(stream, dest, (size_t)size))
return false;
#ifdef PB_VALIDATE_UTF8
if (!pb_validate_utf8((const char*)dest))
PB_RETURN_ERROR(stream, "invalid utf8");
#endif
return true;
}
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_iter_t *field)
{
bool status = true;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
if (field->submsg_desc == NULL)
PB_RETURN_ERROR(stream, "invalid field descriptor");
/* New array entries need to be initialized, while required and optional
* submessages have already been initialized in the top-level pb_decode. */
if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED ||
PB_HTYPE(field->type) == PB_HTYPE_ONEOF)
{
pb_field_iter_t submsg_iter;
if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, field->pData))
{
if (!pb_message_set_to_defaults(&submsg_iter))
PB_RETURN_ERROR(stream, "failed to set defaults");
}
}
/* Submessages can have a separate message-level callback that is called
* before decoding the message. Typically it is used to set callback fields
* inside oneofs. */
if (PB_LTYPE(field->type) == PB_LTYPE_SUBMSG_W_CB && field->pSize != NULL)
{
/* Message callback is stored right before pSize. */
pb_callback_t *callback = (pb_callback_t*)field->pSize - 1;
if (callback->funcs.decode)
{
status = callback->funcs.decode(&substream, field, &callback->arg);
}
}
/* Now decode the submessage contents */
if (status)
{
status = pb_decode_inner(&substream, field->submsg_desc, field->pData, 0);
}
if (!pb_close_string_substream(stream, &substream))
return false;
return status;
}
static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_iter_t *field)
{
uint32_t size;
if (!pb_decode_varint32(stream, &size))
return false;
if (size > PB_SIZE_MAX)
PB_RETURN_ERROR(stream, "bytes overflow");
if (size == 0)
{
/* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */
memset(field->pData, 0, (size_t)field->data_size);
return true;
}
if (size != field->data_size)
PB_RETURN_ERROR(stream, "incorrect fixed length bytes size");
return pb_read(stream, (pb_byte_t*)field->pData, (size_t)field->data_size);
}
#ifdef PB_CONVERT_DOUBLE_FLOAT
bool pb_decode_double_as_float(pb_istream_t *stream, float *dest)
{
uint_least8_t sign;
int exponent;
uint32_t mantissa;
uint64_t value;
union { float f; uint32_t i; } out;
if (!pb_decode_fixed64(stream, &value))
return false;
/* Decompose input value */
sign = (uint_least8_t)((value >> 63) & 1);
exponent = (int)((value >> 52) & 0x7FF) - 1023;
mantissa = (value >> 28) & 0xFFFFFF; /* Highest 24 bits */
/* Figure if value is in range representable by floats. */
if (exponent == 1024)
{
/* Special value */
exponent = 128;
}
else if (exponent > 127)
{
/* Too large, convert to infinity */
exponent = 128;
mantissa = 0;
}
else if (exponent < -150)
{
/* Too small, convert to zero */
exponent = -127;
mantissa = 0;
}
else if (exponent < -126)
{
/* Denormalized */
mantissa |= 0x1000000;
mantissa >>= (-126 - exponent);
exponent = -127;
}
/* Round off mantissa */
mantissa = (mantissa + 1) >> 1;
/* Check if mantissa went over 2.0 */
if (mantissa & 0x800000)
{
exponent += 1;
mantissa &= 0x7FFFFF;
mantissa >>= 1;
}
/* Combine fields */
out.i = mantissa;
out.i |= (uint32_t)(exponent + 127) << 23;
out.i |= (uint32_t)sign << 31;
*dest = out.f;
return true;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4539_0 |
crossvul-cpp_data_good_2657_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994
* 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: IPv6 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 "ip6.h"
#include "ipproto.h"
/*
* If routing headers are presend and valid, set dst to the final destination.
* Otherwise, set it to the IPv6 destination.
*
* This is used for UDP and TCP pseudo-header in the checksum
* calculation.
*/
static void
ip6_finddst(netdissect_options *ndo, struct in6_addr *dst,
const struct ip6_hdr *ip6)
{
const u_char *cp;
int advance;
u_int nh;
const void *dst_addr;
const struct ip6_rthdr *dp;
const struct ip6_rthdr0 *dp0;
const struct in6_addr *addr;
int i, len;
cp = (const u_char *)ip6;
advance = sizeof(struct ip6_hdr);
nh = ip6->ip6_nxt;
dst_addr = (const void *)&ip6->ip6_dst;
while (cp < ndo->ndo_snapend) {
cp += advance;
switch (nh) {
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
case IPPROTO_MOBILITY_OLD:
case IPPROTO_MOBILITY:
/*
* These have a header length byte, following
* the next header byte, giving the length of
* the header, in units of 8 octets, excluding
* the first 8 octets.
*/
ND_TCHECK2(*cp, 2);
advance = (int)((*(cp + 1) + 1) << 3);
nh = *cp;
break;
case IPPROTO_FRAGMENT:
/*
* The byte following the next header byte is
* marked as reserved, and the header is always
* the same size.
*/
ND_TCHECK2(*cp, 1);
advance = sizeof(struct ip6_frag);
nh = *cp;
break;
case IPPROTO_ROUTING:
/*
* OK, we found it.
*/
dp = (const struct ip6_rthdr *)cp;
ND_TCHECK(*dp);
len = dp->ip6r_len;
switch (dp->ip6r_type) {
case IPV6_RTHDR_TYPE_0:
case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */
dp0 = (const struct ip6_rthdr0 *)dp;
if (len % 2 == 1)
goto trunc;
len >>= 1;
addr = &dp0->ip6r0_addr[0];
for (i = 0; i < len; i++) {
if ((const u_char *)(addr + 1) > ndo->ndo_snapend)
goto trunc;
dst_addr = (const void *)addr;
addr++;
}
break;
default:
break;
}
/*
* Only one routing header to a customer.
*/
goto done;
case IPPROTO_AH:
case IPPROTO_ESP:
case IPPROTO_IPCOMP:
default:
/*
* AH and ESP are, in the RFCs that describe them,
* described as being "viewed as an end-to-end
* payload" "in the IPv6 context, so that they
* "should appear after hop-by-hop, routing, and
* fragmentation extension headers". We assume
* that's the case, and stop as soon as we see
* one. (We can't handle an ESP header in
* the general case anyway, as its length depends
* on the encryption algorithm.)
*
* IPComp is also "viewed as an end-to-end
* payload" "in the IPv6 context".
*
* All other protocols are assumed to be the final
* protocol.
*/
goto done;
}
}
done:
trunc:
UNALIGNED_MEMCPY(dst, dst_addr, sizeof(struct in6_addr));
}
/*
* Compute a V6-style checksum by building a pseudoheader.
*/
int
nextproto6_cksum(netdissect_options *ndo,
const struct ip6_hdr *ip6, const uint8_t *data,
u_int len, u_int covlen, u_int next_proto)
{
struct {
struct in6_addr ph_src;
struct in6_addr ph_dst;
uint32_t ph_len;
uint8_t ph_zero[3];
uint8_t ph_nxt;
} ph;
struct cksum_vec vec[2];
/* pseudo-header */
memset(&ph, 0, sizeof(ph));
UNALIGNED_MEMCPY(&ph.ph_src, &ip6->ip6_src, sizeof (struct in6_addr));
switch (ip6->ip6_nxt) {
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
case IPPROTO_MOBILITY_OLD:
case IPPROTO_MOBILITY:
case IPPROTO_FRAGMENT:
case IPPROTO_ROUTING:
/*
* The next header is either a routing header or a header
* after which there might be a routing header, so scan
* for a routing header.
*/
ip6_finddst(ndo, &ph.ph_dst, ip6);
break;
default:
UNALIGNED_MEMCPY(&ph.ph_dst, &ip6->ip6_dst, sizeof (struct in6_addr));
break;
}
ph.ph_len = htonl(len);
ph.ph_nxt = next_proto;
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);
}
/*
* print an IP6 datagram.
*/
void
ip6_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
register const struct ip6_hdr *ip6;
register int advance;
u_int len;
const u_char *ipend;
register const u_char *cp;
register u_int payload_len;
int nh;
int fragmented = 0;
u_int flow;
ip6 = (const struct ip6_hdr *)bp;
ND_TCHECK(*ip6);
if (length < sizeof (struct ip6_hdr)) {
ND_PRINT((ndo, "truncated-ip6 %u", length));
return;
}
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IP6 "));
if (IP6_VERSION(ip6) != 6) {
ND_PRINT((ndo,"version error: %u != 6", IP6_VERSION(ip6)));
return;
}
payload_len = EXTRACT_16BITS(&ip6->ip6_plen);
len = payload_len + sizeof(struct ip6_hdr);
if (length < len)
ND_PRINT((ndo, "truncated-ip6 - %u bytes missing!",
len - length));
if (ndo->ndo_vflag) {
flow = EXTRACT_32BITS(&ip6->ip6_flow);
ND_PRINT((ndo, "("));
#if 0
/* rfc1883 */
if (flow & 0x0f000000)
ND_PRINT((ndo, "pri 0x%02x, ", (flow & 0x0f000000) >> 24));
if (flow & 0x00ffffff)
ND_PRINT((ndo, "flowlabel 0x%06x, ", flow & 0x00ffffff));
#else
/* RFC 2460 */
if (flow & 0x0ff00000)
ND_PRINT((ndo, "class 0x%02x, ", (flow & 0x0ff00000) >> 20));
if (flow & 0x000fffff)
ND_PRINT((ndo, "flowlabel 0x%05x, ", flow & 0x000fffff));
#endif
ND_PRINT((ndo, "hlim %u, next-header %s (%u) payload length: %u) ",
ip6->ip6_hlim,
tok2str(ipproto_values,"unknown",ip6->ip6_nxt),
ip6->ip6_nxt,
payload_len));
}
/*
* Cut off the snapshot length to the end of the IP payload.
*/
ipend = bp + len;
if (ipend < ndo->ndo_snapend)
ndo->ndo_snapend = ipend;
cp = (const u_char *)ip6;
advance = sizeof(struct ip6_hdr);
nh = ip6->ip6_nxt;
while (cp < ndo->ndo_snapend && advance > 0) {
if (len < (u_int)advance)
goto trunc;
cp += advance;
len -= advance;
if (cp == (const u_char *)(ip6 + 1) &&
nh != IPPROTO_TCP && nh != IPPROTO_UDP &&
nh != IPPROTO_DCCP && nh != IPPROTO_SCTP) {
ND_PRINT((ndo, "%s > %s: ", ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
}
switch (nh) {
case IPPROTO_HOPOPTS:
advance = hbhopt_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_DSTOPTS:
advance = dstopt_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_FRAGMENT:
advance = frag6_print(ndo, cp, (const u_char *)ip6);
if (advance < 0 || ndo->ndo_snapend <= cp + advance)
return;
nh = *cp;
fragmented = 1;
break;
case IPPROTO_MOBILITY_OLD:
case IPPROTO_MOBILITY:
/*
* XXX - we don't use "advance"; RFC 3775 says that
* the next header field in a mobility header
* should be IPPROTO_NONE, but speaks of
* the possiblity of a future extension in
* which payload can be piggybacked atop a
* mobility header.
*/
advance = mobility_print(ndo, cp, (const u_char *)ip6);
if (advance < 0)
return;
nh = *cp;
return;
case IPPROTO_ROUTING:
ND_TCHECK(*cp);
advance = rt6_print(ndo, cp, (const u_char *)ip6);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_SCTP:
sctp_print(ndo, cp, (const u_char *)ip6, len);
return;
case IPPROTO_DCCP:
dccp_print(ndo, cp, (const u_char *)ip6, len);
return;
case IPPROTO_TCP:
tcp_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_UDP:
udp_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_ICMPV6:
icmp6_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_AH:
advance = ah_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_ESP:
{
int enh, padlen;
advance = esp_print(ndo, cp, len, (const u_char *)ip6, &enh, &padlen);
if (advance < 0)
return;
nh = enh & 0xff;
len -= padlen;
break;
}
case IPPROTO_IPCOMP:
{
ipcomp_print(ndo, 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.
*/
advance = -1;
break;
}
case IPPROTO_PIM:
pim_print(ndo, cp, len, (const u_char *)ip6);
return;
case IPPROTO_OSPF:
ospf6_print(ndo, cp, len);
return;
case IPPROTO_IPV6:
ip6_print(ndo, cp, len);
return;
case IPPROTO_IPV4:
ip_print(ndo, cp, len);
return;
case IPPROTO_PGM:
pgm_print(ndo, cp, len, (const u_char *)ip6);
return;
case IPPROTO_GRE:
gre_print(ndo, cp, len);
return;
case IPPROTO_RSVP:
rsvp_print(ndo, cp, len);
return;
case IPPROTO_NONE:
ND_PRINT((ndo, "no next header"));
return;
default:
ND_PRINT((ndo, "ip-proto-%d %d", nh, len));
return;
}
}
return;
trunc:
ND_PRINT((ndo, "[|ip6]"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2657_0 |
crossvul-cpp_data_bad_2914_0 | /*
* USB HID support for Linux
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
* Copyright (c) 2007-2008 Oliver Neukum
* Copyright (c) 2006-2010 Jiri Kosina
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/mutex.h>
#include <linux/spinlock.h>
#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <linux/input.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/string.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include <linux/hiddev.h>
#include <linux/hid-debug.h>
#include <linux/hidraw.h>
#include "usbhid.h"
/*
* Version Information
*/
#define DRIVER_DESC "USB HID core driver"
/*
* Module parameters.
*/
static unsigned int hid_mousepoll_interval;
module_param_named(mousepoll, hid_mousepoll_interval, uint, 0644);
MODULE_PARM_DESC(mousepoll, "Polling interval of mice");
static unsigned int hid_jspoll_interval;
module_param_named(jspoll, hid_jspoll_interval, uint, 0644);
MODULE_PARM_DESC(jspoll, "Polling interval of joysticks");
static unsigned int ignoreled;
module_param_named(ignoreled, ignoreled, uint, 0644);
MODULE_PARM_DESC(ignoreled, "Autosuspend with active leds");
/* Quirks specified at module load time */
static char *quirks_param[MAX_USBHID_BOOT_QUIRKS];
module_param_array_named(quirks, quirks_param, charp, NULL, 0444);
MODULE_PARM_DESC(quirks, "Add/modify USB HID quirks by specifying "
" quirks=vendorID:productID:quirks"
" where vendorID, productID, and quirks are all in"
" 0x-prefixed hex");
/*
* Input submission and I/O error handler.
*/
static void hid_io_error(struct hid_device *hid);
static int hid_submit_out(struct hid_device *hid);
static int hid_submit_ctrl(struct hid_device *hid);
static void hid_cancel_delayed_stuff(struct usbhid_device *usbhid);
/* Start up the input URB */
static int hid_start_in(struct hid_device *hid)
{
unsigned long flags;
int rc = 0;
struct usbhid_device *usbhid = hid->driver_data;
spin_lock_irqsave(&usbhid->lock, flags);
if (test_bit(HID_IN_POLLING, &usbhid->iofl) &&
!test_bit(HID_DISCONNECTED, &usbhid->iofl) &&
!test_bit(HID_SUSPENDED, &usbhid->iofl) &&
!test_and_set_bit(HID_IN_RUNNING, &usbhid->iofl)) {
rc = usb_submit_urb(usbhid->urbin, GFP_ATOMIC);
if (rc != 0) {
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
if (rc == -ENOSPC)
set_bit(HID_NO_BANDWIDTH, &usbhid->iofl);
} else {
clear_bit(HID_NO_BANDWIDTH, &usbhid->iofl);
}
}
spin_unlock_irqrestore(&usbhid->lock, flags);
return rc;
}
/* I/O retry timer routine */
static void hid_retry_timeout(unsigned long _hid)
{
struct hid_device *hid = (struct hid_device *) _hid;
struct usbhid_device *usbhid = hid->driver_data;
dev_dbg(&usbhid->intf->dev, "retrying intr urb\n");
if (hid_start_in(hid))
hid_io_error(hid);
}
/* Workqueue routine to reset the device or clear a halt */
static void hid_reset(struct work_struct *work)
{
struct usbhid_device *usbhid =
container_of(work, struct usbhid_device, reset_work);
struct hid_device *hid = usbhid->hid;
int rc;
if (test_bit(HID_CLEAR_HALT, &usbhid->iofl)) {
dev_dbg(&usbhid->intf->dev, "clear halt\n");
rc = usb_clear_halt(hid_to_usb_dev(hid), usbhid->urbin->pipe);
clear_bit(HID_CLEAR_HALT, &usbhid->iofl);
if (rc == 0) {
hid_start_in(hid);
} else {
dev_dbg(&usbhid->intf->dev,
"clear-halt failed: %d\n", rc);
set_bit(HID_RESET_PENDING, &usbhid->iofl);
}
}
if (test_bit(HID_RESET_PENDING, &usbhid->iofl)) {
dev_dbg(&usbhid->intf->dev, "resetting device\n");
usb_queue_reset_device(usbhid->intf);
}
}
/* Main I/O error handler */
static void hid_io_error(struct hid_device *hid)
{
unsigned long flags;
struct usbhid_device *usbhid = hid->driver_data;
spin_lock_irqsave(&usbhid->lock, flags);
/* Stop when disconnected */
if (test_bit(HID_DISCONNECTED, &usbhid->iofl))
goto done;
/* If it has been a while since the last error, we'll assume
* this a brand new error and reset the retry timeout. */
if (time_after(jiffies, usbhid->stop_retry + HZ/2))
usbhid->retry_delay = 0;
/* When an error occurs, retry at increasing intervals */
if (usbhid->retry_delay == 0) {
usbhid->retry_delay = 13; /* Then 26, 52, 104, 104, ... */
usbhid->stop_retry = jiffies + msecs_to_jiffies(1000);
} else if (usbhid->retry_delay < 100)
usbhid->retry_delay *= 2;
if (time_after(jiffies, usbhid->stop_retry)) {
/* Retries failed, so do a port reset unless we lack bandwidth*/
if (!test_bit(HID_NO_BANDWIDTH, &usbhid->iofl)
&& !test_and_set_bit(HID_RESET_PENDING, &usbhid->iofl)) {
schedule_work(&usbhid->reset_work);
goto done;
}
}
mod_timer(&usbhid->io_retry,
jiffies + msecs_to_jiffies(usbhid->retry_delay));
done:
spin_unlock_irqrestore(&usbhid->lock, flags);
}
static void usbhid_mark_busy(struct usbhid_device *usbhid)
{
struct usb_interface *intf = usbhid->intf;
usb_mark_last_busy(interface_to_usbdev(intf));
}
static int usbhid_restart_out_queue(struct usbhid_device *usbhid)
{
struct hid_device *hid = usb_get_intfdata(usbhid->intf);
int kicked;
int r;
if (!hid || test_bit(HID_RESET_PENDING, &usbhid->iofl) ||
test_bit(HID_SUSPENDED, &usbhid->iofl))
return 0;
if ((kicked = (usbhid->outhead != usbhid->outtail))) {
hid_dbg(hid, "Kicking head %d tail %d", usbhid->outhead, usbhid->outtail);
/* Try to wake up from autosuspend... */
r = usb_autopm_get_interface_async(usbhid->intf);
if (r < 0)
return r;
/*
* If still suspended, don't submit. Submission will
* occur if/when resume drains the queue.
*/
if (test_bit(HID_SUSPENDED, &usbhid->iofl)) {
usb_autopm_put_interface_no_suspend(usbhid->intf);
return r;
}
/* Asynchronously flush queue. */
set_bit(HID_OUT_RUNNING, &usbhid->iofl);
if (hid_submit_out(hid)) {
clear_bit(HID_OUT_RUNNING, &usbhid->iofl);
usb_autopm_put_interface_async(usbhid->intf);
}
wake_up(&usbhid->wait);
}
return kicked;
}
static int usbhid_restart_ctrl_queue(struct usbhid_device *usbhid)
{
struct hid_device *hid = usb_get_intfdata(usbhid->intf);
int kicked;
int r;
WARN_ON(hid == NULL);
if (!hid || test_bit(HID_RESET_PENDING, &usbhid->iofl) ||
test_bit(HID_SUSPENDED, &usbhid->iofl))
return 0;
if ((kicked = (usbhid->ctrlhead != usbhid->ctrltail))) {
hid_dbg(hid, "Kicking head %d tail %d", usbhid->ctrlhead, usbhid->ctrltail);
/* Try to wake up from autosuspend... */
r = usb_autopm_get_interface_async(usbhid->intf);
if (r < 0)
return r;
/*
* If still suspended, don't submit. Submission will
* occur if/when resume drains the queue.
*/
if (test_bit(HID_SUSPENDED, &usbhid->iofl)) {
usb_autopm_put_interface_no_suspend(usbhid->intf);
return r;
}
/* Asynchronously flush queue. */
set_bit(HID_CTRL_RUNNING, &usbhid->iofl);
if (hid_submit_ctrl(hid)) {
clear_bit(HID_CTRL_RUNNING, &usbhid->iofl);
usb_autopm_put_interface_async(usbhid->intf);
}
wake_up(&usbhid->wait);
}
return kicked;
}
/*
* Input interrupt completion handler.
*/
static void hid_irq_in(struct urb *urb)
{
struct hid_device *hid = urb->context;
struct usbhid_device *usbhid = hid->driver_data;
int status;
switch (urb->status) {
case 0: /* success */
usbhid->retry_delay = 0;
if (!test_bit(HID_OPENED, &usbhid->iofl))
break;
usbhid_mark_busy(usbhid);
if (!test_bit(HID_RESUME_RUNNING, &usbhid->iofl)) {
hid_input_report(urb->context, HID_INPUT_REPORT,
urb->transfer_buffer,
urb->actual_length, 1);
/*
* autosuspend refused while keys are pressed
* because most keyboards don't wake up when
* a key is released
*/
if (hid_check_keys_pressed(hid))
set_bit(HID_KEYS_PRESSED, &usbhid->iofl);
else
clear_bit(HID_KEYS_PRESSED, &usbhid->iofl);
}
break;
case -EPIPE: /* stall */
usbhid_mark_busy(usbhid);
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
set_bit(HID_CLEAR_HALT, &usbhid->iofl);
schedule_work(&usbhid->reset_work);
return;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN: /* unplug */
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
return;
case -EILSEQ: /* protocol error or unplug */
case -EPROTO: /* protocol error or unplug */
case -ETIME: /* protocol error or unplug */
case -ETIMEDOUT: /* Should never happen, but... */
usbhid_mark_busy(usbhid);
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
hid_io_error(hid);
return;
default: /* error */
hid_warn(urb->dev, "input irq status %d received\n",
urb->status);
}
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status) {
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
if (status != -EPERM) {
hid_err(hid, "can't resubmit intr, %s-%s/input%d, status %d\n",
hid_to_usb_dev(hid)->bus->bus_name,
hid_to_usb_dev(hid)->devpath,
usbhid->ifnum, status);
hid_io_error(hid);
}
}
}
static int hid_submit_out(struct hid_device *hid)
{
struct hid_report *report;
char *raw_report;
struct usbhid_device *usbhid = hid->driver_data;
int r;
report = usbhid->out[usbhid->outtail].report;
raw_report = usbhid->out[usbhid->outtail].raw_report;
usbhid->urbout->transfer_buffer_length = hid_report_len(report);
usbhid->urbout->dev = hid_to_usb_dev(hid);
if (raw_report) {
memcpy(usbhid->outbuf, raw_report,
usbhid->urbout->transfer_buffer_length);
kfree(raw_report);
usbhid->out[usbhid->outtail].raw_report = NULL;
}
dbg_hid("submitting out urb\n");
r = usb_submit_urb(usbhid->urbout, GFP_ATOMIC);
if (r < 0) {
hid_err(hid, "usb_submit_urb(out) failed: %d\n", r);
return r;
}
usbhid->last_out = jiffies;
return 0;
}
static int hid_submit_ctrl(struct hid_device *hid)
{
struct hid_report *report;
unsigned char dir;
char *raw_report;
int len, r;
struct usbhid_device *usbhid = hid->driver_data;
report = usbhid->ctrl[usbhid->ctrltail].report;
raw_report = usbhid->ctrl[usbhid->ctrltail].raw_report;
dir = usbhid->ctrl[usbhid->ctrltail].dir;
len = ((report->size - 1) >> 3) + 1 + (report->id > 0);
if (dir == USB_DIR_OUT) {
usbhid->urbctrl->pipe = usb_sndctrlpipe(hid_to_usb_dev(hid), 0);
usbhid->urbctrl->transfer_buffer_length = len;
if (raw_report) {
memcpy(usbhid->ctrlbuf, raw_report, len);
kfree(raw_report);
usbhid->ctrl[usbhid->ctrltail].raw_report = NULL;
}
} else {
int maxpacket, padlen;
usbhid->urbctrl->pipe = usb_rcvctrlpipe(hid_to_usb_dev(hid), 0);
maxpacket = usb_maxpacket(hid_to_usb_dev(hid),
usbhid->urbctrl->pipe, 0);
if (maxpacket > 0) {
padlen = DIV_ROUND_UP(len, maxpacket);
padlen *= maxpacket;
if (padlen > usbhid->bufsize)
padlen = usbhid->bufsize;
} else
padlen = 0;
usbhid->urbctrl->transfer_buffer_length = padlen;
}
usbhid->urbctrl->dev = hid_to_usb_dev(hid);
usbhid->cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE | dir;
usbhid->cr->bRequest = (dir == USB_DIR_OUT) ? HID_REQ_SET_REPORT :
HID_REQ_GET_REPORT;
usbhid->cr->wValue = cpu_to_le16(((report->type + 1) << 8) |
report->id);
usbhid->cr->wIndex = cpu_to_le16(usbhid->ifnum);
usbhid->cr->wLength = cpu_to_le16(len);
dbg_hid("submitting ctrl urb: %s wValue=0x%04x wIndex=0x%04x wLength=%u\n",
usbhid->cr->bRequest == HID_REQ_SET_REPORT ? "Set_Report" :
"Get_Report",
usbhid->cr->wValue, usbhid->cr->wIndex, usbhid->cr->wLength);
r = usb_submit_urb(usbhid->urbctrl, GFP_ATOMIC);
if (r < 0) {
hid_err(hid, "usb_submit_urb(ctrl) failed: %d\n", r);
return r;
}
usbhid->last_ctrl = jiffies;
return 0;
}
/*
* Output interrupt completion handler.
*/
static void hid_irq_out(struct urb *urb)
{
struct hid_device *hid = urb->context;
struct usbhid_device *usbhid = hid->driver_data;
unsigned long flags;
int unplug = 0;
switch (urb->status) {
case 0: /* success */
break;
case -ESHUTDOWN: /* unplug */
unplug = 1;
case -EILSEQ: /* protocol error or unplug */
case -EPROTO: /* protocol error or unplug */
case -ECONNRESET: /* unlink */
case -ENOENT:
break;
default: /* error */
hid_warn(urb->dev, "output irq status %d received\n",
urb->status);
}
spin_lock_irqsave(&usbhid->lock, flags);
if (unplug) {
usbhid->outtail = usbhid->outhead;
} else {
usbhid->outtail = (usbhid->outtail + 1) & (HID_OUTPUT_FIFO_SIZE - 1);
if (usbhid->outhead != usbhid->outtail &&
hid_submit_out(hid) == 0) {
/* Successfully submitted next urb in queue */
spin_unlock_irqrestore(&usbhid->lock, flags);
return;
}
}
clear_bit(HID_OUT_RUNNING, &usbhid->iofl);
spin_unlock_irqrestore(&usbhid->lock, flags);
usb_autopm_put_interface_async(usbhid->intf);
wake_up(&usbhid->wait);
}
/*
* Control pipe completion handler.
*/
static void hid_ctrl(struct urb *urb)
{
struct hid_device *hid = urb->context;
struct usbhid_device *usbhid = hid->driver_data;
int unplug = 0, status = urb->status;
switch (status) {
case 0: /* success */
if (usbhid->ctrl[usbhid->ctrltail].dir == USB_DIR_IN)
hid_input_report(urb->context,
usbhid->ctrl[usbhid->ctrltail].report->type,
urb->transfer_buffer, urb->actual_length, 0);
break;
case -ESHUTDOWN: /* unplug */
unplug = 1;
case -EILSEQ: /* protocol error or unplug */
case -EPROTO: /* protocol error or unplug */
case -ECONNRESET: /* unlink */
case -ENOENT:
case -EPIPE: /* report not available */
break;
default: /* error */
hid_warn(urb->dev, "ctrl urb status %d received\n", status);
}
spin_lock(&usbhid->lock);
if (unplug) {
usbhid->ctrltail = usbhid->ctrlhead;
} else {
usbhid->ctrltail = (usbhid->ctrltail + 1) & (HID_CONTROL_FIFO_SIZE - 1);
if (usbhid->ctrlhead != usbhid->ctrltail &&
hid_submit_ctrl(hid) == 0) {
/* Successfully submitted next urb in queue */
spin_unlock(&usbhid->lock);
return;
}
}
clear_bit(HID_CTRL_RUNNING, &usbhid->iofl);
spin_unlock(&usbhid->lock);
usb_autopm_put_interface_async(usbhid->intf);
wake_up(&usbhid->wait);
}
static void __usbhid_submit_report(struct hid_device *hid, struct hid_report *report,
unsigned char dir)
{
int head;
struct usbhid_device *usbhid = hid->driver_data;
if (((hid->quirks & HID_QUIRK_NOGET) && dir == USB_DIR_IN) ||
test_bit(HID_DISCONNECTED, &usbhid->iofl))
return;
if (usbhid->urbout && dir == USB_DIR_OUT && report->type == HID_OUTPUT_REPORT) {
if ((head = (usbhid->outhead + 1) & (HID_OUTPUT_FIFO_SIZE - 1)) == usbhid->outtail) {
hid_warn(hid, "output queue full\n");
return;
}
usbhid->out[usbhid->outhead].raw_report = hid_alloc_report_buf(report, GFP_ATOMIC);
if (!usbhid->out[usbhid->outhead].raw_report) {
hid_warn(hid, "output queueing failed\n");
return;
}
hid_output_report(report, usbhid->out[usbhid->outhead].raw_report);
usbhid->out[usbhid->outhead].report = report;
usbhid->outhead = head;
/* If the queue isn't running, restart it */
if (!test_bit(HID_OUT_RUNNING, &usbhid->iofl)) {
usbhid_restart_out_queue(usbhid);
/* Otherwise see if an earlier request has timed out */
} else if (time_after(jiffies, usbhid->last_out + HZ * 5)) {
/* Prevent autosuspend following the unlink */
usb_autopm_get_interface_no_resume(usbhid->intf);
/*
* Prevent resubmission in case the URB completes
* before we can unlink it. We don't want to cancel
* the wrong transfer!
*/
usb_block_urb(usbhid->urbout);
/* Drop lock to avoid deadlock if the callback runs */
spin_unlock(&usbhid->lock);
usb_unlink_urb(usbhid->urbout);
spin_lock(&usbhid->lock);
usb_unblock_urb(usbhid->urbout);
/* Unlink might have stopped the queue */
if (!test_bit(HID_OUT_RUNNING, &usbhid->iofl))
usbhid_restart_out_queue(usbhid);
/* Now we can allow autosuspend again */
usb_autopm_put_interface_async(usbhid->intf);
}
return;
}
if ((head = (usbhid->ctrlhead + 1) & (HID_CONTROL_FIFO_SIZE - 1)) == usbhid->ctrltail) {
hid_warn(hid, "control queue full\n");
return;
}
if (dir == USB_DIR_OUT) {
usbhid->ctrl[usbhid->ctrlhead].raw_report = hid_alloc_report_buf(report, GFP_ATOMIC);
if (!usbhid->ctrl[usbhid->ctrlhead].raw_report) {
hid_warn(hid, "control queueing failed\n");
return;
}
hid_output_report(report, usbhid->ctrl[usbhid->ctrlhead].raw_report);
}
usbhid->ctrl[usbhid->ctrlhead].report = report;
usbhid->ctrl[usbhid->ctrlhead].dir = dir;
usbhid->ctrlhead = head;
/* If the queue isn't running, restart it */
if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl)) {
usbhid_restart_ctrl_queue(usbhid);
/* Otherwise see if an earlier request has timed out */
} else if (time_after(jiffies, usbhid->last_ctrl + HZ * 5)) {
/* Prevent autosuspend following the unlink */
usb_autopm_get_interface_no_resume(usbhid->intf);
/*
* Prevent resubmission in case the URB completes
* before we can unlink it. We don't want to cancel
* the wrong transfer!
*/
usb_block_urb(usbhid->urbctrl);
/* Drop lock to avoid deadlock if the callback runs */
spin_unlock(&usbhid->lock);
usb_unlink_urb(usbhid->urbctrl);
spin_lock(&usbhid->lock);
usb_unblock_urb(usbhid->urbctrl);
/* Unlink might have stopped the queue */
if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
usbhid_restart_ctrl_queue(usbhid);
/* Now we can allow autosuspend again */
usb_autopm_put_interface_async(usbhid->intf);
}
}
static void usbhid_submit_report(struct hid_device *hid, struct hid_report *report, unsigned char dir)
{
struct usbhid_device *usbhid = hid->driver_data;
unsigned long flags;
spin_lock_irqsave(&usbhid->lock, flags);
__usbhid_submit_report(hid, report, dir);
spin_unlock_irqrestore(&usbhid->lock, flags);
}
static int usbhid_wait_io(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
if (!wait_event_timeout(usbhid->wait,
(!test_bit(HID_CTRL_RUNNING, &usbhid->iofl) &&
!test_bit(HID_OUT_RUNNING, &usbhid->iofl)),
10*HZ)) {
dbg_hid("timeout waiting for ctrl or out queue to clear\n");
return -1;
}
return 0;
}
static int hid_set_idle(struct usb_device *dev, int ifnum, int report, int idle)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
HID_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE, (idle << 8) | report,
ifnum, NULL, 0, USB_CTRL_SET_TIMEOUT);
}
static int hid_get_class_descriptor(struct usb_device *dev, int ifnum,
unsigned char type, void *buf, int size)
{
int result, retries = 4;
memset(buf, 0, size);
do {
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
(type << 8), ifnum, buf, size, USB_CTRL_GET_TIMEOUT);
retries--;
} while (result < size && retries);
return result;
}
static int usbhid_open(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
int res;
set_bit(HID_OPENED, &usbhid->iofl);
if (hid->quirks & HID_QUIRK_ALWAYS_POLL)
return 0;
res = usb_autopm_get_interface(usbhid->intf);
/* the device must be awake to reliably request remote wakeup */
if (res < 0) {
clear_bit(HID_OPENED, &usbhid->iofl);
return -EIO;
}
usbhid->intf->needs_remote_wakeup = 1;
set_bit(HID_RESUME_RUNNING, &usbhid->iofl);
set_bit(HID_IN_POLLING, &usbhid->iofl);
res = hid_start_in(hid);
if (res) {
if (res != -ENOSPC) {
hid_io_error(hid);
res = 0;
} else {
/* no use opening if resources are insufficient */
res = -EBUSY;
clear_bit(HID_OPENED, &usbhid->iofl);
clear_bit(HID_IN_POLLING, &usbhid->iofl);
usbhid->intf->needs_remote_wakeup = 0;
}
}
usb_autopm_put_interface(usbhid->intf);
/*
* In case events are generated while nobody was listening,
* some are released when the device is re-opened.
* Wait 50 msec for the queue to empty before allowing events
* to go through hid.
*/
if (res == 0)
msleep(50);
clear_bit(HID_RESUME_RUNNING, &usbhid->iofl);
return res;
}
static void usbhid_close(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
/*
* Make sure we don't restart data acquisition due to
* a resumption we no longer care about by avoiding racing
* with hid_start_in().
*/
spin_lock_irq(&usbhid->lock);
clear_bit(HID_OPENED, &usbhid->iofl);
if (!(hid->quirks & HID_QUIRK_ALWAYS_POLL))
clear_bit(HID_IN_POLLING, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
if (hid->quirks & HID_QUIRK_ALWAYS_POLL)
return;
hid_cancel_delayed_stuff(usbhid);
usb_kill_urb(usbhid->urbin);
usbhid->intf->needs_remote_wakeup = 0;
}
/*
* Initialize all reports
*/
void usbhid_init_reports(struct hid_device *hid)
{
struct hid_report *report;
struct usbhid_device *usbhid = hid->driver_data;
struct hid_report_enum *report_enum;
int err, ret;
report_enum = &hid->report_enum[HID_INPUT_REPORT];
list_for_each_entry(report, &report_enum->report_list, list)
usbhid_submit_report(hid, report, USB_DIR_IN);
report_enum = &hid->report_enum[HID_FEATURE_REPORT];
list_for_each_entry(report, &report_enum->report_list, list)
usbhid_submit_report(hid, report, USB_DIR_IN);
err = 0;
ret = usbhid_wait_io(hid);
while (ret) {
err |= ret;
if (test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
usb_kill_urb(usbhid->urbctrl);
if (test_bit(HID_OUT_RUNNING, &usbhid->iofl))
usb_kill_urb(usbhid->urbout);
ret = usbhid_wait_io(hid);
}
if (err)
hid_warn(hid, "timeout initializing reports\n");
}
/*
* Reset LEDs which BIOS might have left on. For now, just NumLock (0x01).
*/
static int hid_find_field_early(struct hid_device *hid, unsigned int page,
unsigned int hid_code, struct hid_field **pfield)
{
struct hid_report *report;
struct hid_field *field;
struct hid_usage *usage;
int i, j;
list_for_each_entry(report, &hid->report_enum[HID_OUTPUT_REPORT].report_list, list) {
for (i = 0; i < report->maxfield; i++) {
field = report->field[i];
for (j = 0; j < field->maxusage; j++) {
usage = &field->usage[j];
if ((usage->hid & HID_USAGE_PAGE) == page &&
(usage->hid & 0xFFFF) == hid_code) {
*pfield = field;
return j;
}
}
}
}
return -1;
}
static void usbhid_set_leds(struct hid_device *hid)
{
struct hid_field *field;
int offset;
if ((offset = hid_find_field_early(hid, HID_UP_LED, 0x01, &field)) != -1) {
hid_set_field(field, offset, 0);
usbhid_submit_report(hid, field->report, USB_DIR_OUT);
}
}
/*
* Traverse the supplied list of reports and find the longest
*/
static void hid_find_max_report(struct hid_device *hid, unsigned int type,
unsigned int *max)
{
struct hid_report *report;
unsigned int size;
list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
size = ((report->size - 1) >> 3) + 1 + hid->report_enum[type].numbered;
if (*max < size)
*max = size;
}
}
static int hid_alloc_buffers(struct usb_device *dev, struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
usbhid->inbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
&usbhid->inbuf_dma);
usbhid->outbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
&usbhid->outbuf_dma);
usbhid->cr = kmalloc(sizeof(*usbhid->cr), GFP_KERNEL);
usbhid->ctrlbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
&usbhid->ctrlbuf_dma);
if (!usbhid->inbuf || !usbhid->outbuf || !usbhid->cr ||
!usbhid->ctrlbuf)
return -1;
return 0;
}
static int usbhid_get_raw_report(struct hid_device *hid,
unsigned char report_number, __u8 *buf, size_t count,
unsigned char report_type)
{
struct usbhid_device *usbhid = hid->driver_data;
struct usb_device *dev = hid_to_usb_dev(hid);
struct usb_interface *intf = usbhid->intf;
struct usb_host_interface *interface = intf->cur_altsetting;
int skipped_report_id = 0;
int ret;
/* Byte 0 is the report number. Report data starts at byte 1.*/
buf[0] = report_number;
if (report_number == 0x0) {
/* Offset the return buffer by 1, so that the report ID
will remain in byte 0. */
buf++;
count--;
skipped_report_id = 1;
}
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
HID_REQ_GET_REPORT,
USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
((report_type + 1) << 8) | report_number,
interface->desc.bInterfaceNumber, buf, count,
USB_CTRL_SET_TIMEOUT);
/* count also the report id */
if (ret > 0 && skipped_report_id)
ret++;
return ret;
}
static int usbhid_set_raw_report(struct hid_device *hid, unsigned int reportnum,
__u8 *buf, size_t count, unsigned char rtype)
{
struct usbhid_device *usbhid = hid->driver_data;
struct usb_device *dev = hid_to_usb_dev(hid);
struct usb_interface *intf = usbhid->intf;
struct usb_host_interface *interface = intf->cur_altsetting;
int ret, skipped_report_id = 0;
/* Byte 0 is the report number. Report data starts at byte 1.*/
if ((rtype == HID_OUTPUT_REPORT) &&
(hid->quirks & HID_QUIRK_SKIP_OUTPUT_REPORT_ID))
buf[0] = 0;
else
buf[0] = reportnum;
if (buf[0] == 0x0) {
/* Don't send the Report ID */
buf++;
count--;
skipped_report_id = 1;
}
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
HID_REQ_SET_REPORT,
USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
((rtype + 1) << 8) | reportnum,
interface->desc.bInterfaceNumber, buf, count,
USB_CTRL_SET_TIMEOUT);
/* count also the report id, if this was a numbered report. */
if (ret > 0 && skipped_report_id)
ret++;
return ret;
}
static int usbhid_output_report(struct hid_device *hid, __u8 *buf, size_t count)
{
struct usbhid_device *usbhid = hid->driver_data;
struct usb_device *dev = hid_to_usb_dev(hid);
int actual_length, skipped_report_id = 0, ret;
if (!usbhid->urbout)
return -ENOSYS;
if (buf[0] == 0x0) {
/* Don't send the Report ID */
buf++;
count--;
skipped_report_id = 1;
}
ret = usb_interrupt_msg(dev, usbhid->urbout->pipe,
buf, count, &actual_length,
USB_CTRL_SET_TIMEOUT);
/* return the number of bytes transferred */
if (ret == 0) {
ret = actual_length;
/* count also the report id */
if (skipped_report_id)
ret++;
}
return ret;
}
static void hid_free_buffers(struct usb_device *dev, struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
usb_free_coherent(dev, usbhid->bufsize, usbhid->inbuf, usbhid->inbuf_dma);
usb_free_coherent(dev, usbhid->bufsize, usbhid->outbuf, usbhid->outbuf_dma);
kfree(usbhid->cr);
usb_free_coherent(dev, usbhid->bufsize, usbhid->ctrlbuf, usbhid->ctrlbuf_dma);
}
static int usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
for (n = 0; n < hdesc->bNumDescriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
rdesc = kmalloc(rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
}
static int usbhid_start(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev(intf);
struct usbhid_device *usbhid = hid->driver_data;
unsigned int n, insize = 0;
int ret;
clear_bit(HID_DISCONNECTED, &usbhid->iofl);
usbhid->bufsize = HID_MIN_BUFFER_SIZE;
hid_find_max_report(hid, HID_INPUT_REPORT, &usbhid->bufsize);
hid_find_max_report(hid, HID_OUTPUT_REPORT, &usbhid->bufsize);
hid_find_max_report(hid, HID_FEATURE_REPORT, &usbhid->bufsize);
if (usbhid->bufsize > HID_MAX_BUFFER_SIZE)
usbhid->bufsize = HID_MAX_BUFFER_SIZE;
hid_find_max_report(hid, HID_INPUT_REPORT, &insize);
if (insize > HID_MAX_BUFFER_SIZE)
insize = HID_MAX_BUFFER_SIZE;
if (hid_alloc_buffers(dev, hid)) {
ret = -ENOMEM;
goto fail;
}
for (n = 0; n < interface->desc.bNumEndpoints; n++) {
struct usb_endpoint_descriptor *endpoint;
int pipe;
int interval;
endpoint = &interface->endpoint[n].desc;
if (!usb_endpoint_xfer_int(endpoint))
continue;
interval = endpoint->bInterval;
/* Some vendors give fullspeed interval on highspeed devides */
if (hid->quirks & HID_QUIRK_FULLSPEED_INTERVAL &&
dev->speed == USB_SPEED_HIGH) {
interval = fls(endpoint->bInterval*8);
pr_info("%s: Fixing fullspeed to highspeed interval: %d -> %d\n",
hid->name, endpoint->bInterval, interval);
}
/* Change the polling interval of mice and joysticks. */
switch (hid->collection->usage) {
case HID_GD_MOUSE:
if (hid_mousepoll_interval > 0)
interval = hid_mousepoll_interval;
break;
case HID_GD_JOYSTICK:
if (hid_jspoll_interval > 0)
interval = hid_jspoll_interval;
break;
}
ret = -ENOMEM;
if (usb_endpoint_dir_in(endpoint)) {
if (usbhid->urbin)
continue;
if (!(usbhid->urbin = usb_alloc_urb(0, GFP_KERNEL)))
goto fail;
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
usb_fill_int_urb(usbhid->urbin, dev, pipe, usbhid->inbuf, insize,
hid_irq_in, hid, interval);
usbhid->urbin->transfer_dma = usbhid->inbuf_dma;
usbhid->urbin->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
} else {
if (usbhid->urbout)
continue;
if (!(usbhid->urbout = usb_alloc_urb(0, GFP_KERNEL)))
goto fail;
pipe = usb_sndintpipe(dev, endpoint->bEndpointAddress);
usb_fill_int_urb(usbhid->urbout, dev, pipe, usbhid->outbuf, 0,
hid_irq_out, hid, interval);
usbhid->urbout->transfer_dma = usbhid->outbuf_dma;
usbhid->urbout->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
}
}
usbhid->urbctrl = usb_alloc_urb(0, GFP_KERNEL);
if (!usbhid->urbctrl) {
ret = -ENOMEM;
goto fail;
}
usb_fill_control_urb(usbhid->urbctrl, dev, 0, (void *) usbhid->cr,
usbhid->ctrlbuf, 1, hid_ctrl, hid);
usbhid->urbctrl->transfer_dma = usbhid->ctrlbuf_dma;
usbhid->urbctrl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
set_bit(HID_STARTED, &usbhid->iofl);
if (hid->quirks & HID_QUIRK_ALWAYS_POLL) {
ret = usb_autopm_get_interface(usbhid->intf);
if (ret)
goto fail;
set_bit(HID_IN_POLLING, &usbhid->iofl);
usbhid->intf->needs_remote_wakeup = 1;
ret = hid_start_in(hid);
if (ret) {
dev_err(&hid->dev,
"failed to start in urb: %d\n", ret);
}
usb_autopm_put_interface(usbhid->intf);
}
/* Some keyboards don't work until their LEDs have been set.
* Since BIOSes do set the LEDs, it must be safe for any device
* that supports the keyboard boot protocol.
* In addition, enable remote wakeup by default for all keyboard
* devices supporting the boot protocol.
*/
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT &&
interface->desc.bInterfaceProtocol ==
USB_INTERFACE_PROTOCOL_KEYBOARD) {
usbhid_set_leds(hid);
device_set_wakeup_enable(&dev->dev, 1);
}
return 0;
fail:
usb_free_urb(usbhid->urbin);
usb_free_urb(usbhid->urbout);
usb_free_urb(usbhid->urbctrl);
usbhid->urbin = NULL;
usbhid->urbout = NULL;
usbhid->urbctrl = NULL;
hid_free_buffers(dev, hid);
return ret;
}
static void usbhid_stop(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
if (WARN_ON(!usbhid))
return;
if (hid->quirks & HID_QUIRK_ALWAYS_POLL) {
clear_bit(HID_IN_POLLING, &usbhid->iofl);
usbhid->intf->needs_remote_wakeup = 0;
}
clear_bit(HID_STARTED, &usbhid->iofl);
spin_lock_irq(&usbhid->lock); /* Sync with error and led handlers */
set_bit(HID_DISCONNECTED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
usb_kill_urb(usbhid->urbin);
usb_kill_urb(usbhid->urbout);
usb_kill_urb(usbhid->urbctrl);
hid_cancel_delayed_stuff(usbhid);
hid->claimed = 0;
usb_free_urb(usbhid->urbin);
usb_free_urb(usbhid->urbctrl);
usb_free_urb(usbhid->urbout);
usbhid->urbin = NULL; /* don't mess up next start */
usbhid->urbctrl = NULL;
usbhid->urbout = NULL;
hid_free_buffers(hid_to_usb_dev(hid), hid);
}
static int usbhid_power(struct hid_device *hid, int lvl)
{
struct usbhid_device *usbhid = hid->driver_data;
int r = 0;
switch (lvl) {
case PM_HINT_FULLON:
r = usb_autopm_get_interface(usbhid->intf);
break;
case PM_HINT_NORMAL:
usb_autopm_put_interface(usbhid->intf);
break;
}
return r;
}
static void usbhid_request(struct hid_device *hid, struct hid_report *rep, int reqtype)
{
switch (reqtype) {
case HID_REQ_GET_REPORT:
usbhid_submit_report(hid, rep, USB_DIR_IN);
break;
case HID_REQ_SET_REPORT:
usbhid_submit_report(hid, rep, USB_DIR_OUT);
break;
}
}
static int usbhid_raw_request(struct hid_device *hid, unsigned char reportnum,
__u8 *buf, size_t len, unsigned char rtype,
int reqtype)
{
switch (reqtype) {
case HID_REQ_GET_REPORT:
return usbhid_get_raw_report(hid, reportnum, buf, len, rtype);
case HID_REQ_SET_REPORT:
return usbhid_set_raw_report(hid, reportnum, buf, len, rtype);
default:
return -EIO;
}
}
static int usbhid_idle(struct hid_device *hid, int report, int idle,
int reqtype)
{
struct usb_device *dev = hid_to_usb_dev(hid);
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
int ifnum = interface->desc.bInterfaceNumber;
if (reqtype != HID_REQ_SET_IDLE)
return -EINVAL;
return hid_set_idle(dev, ifnum, report, idle);
}
struct hid_ll_driver usb_hid_driver = {
.parse = usbhid_parse,
.start = usbhid_start,
.stop = usbhid_stop,
.open = usbhid_open,
.close = usbhid_close,
.power = usbhid_power,
.request = usbhid_request,
.wait = usbhid_wait_io,
.raw_request = usbhid_raw_request,
.output_report = usbhid_output_report,
.idle = usbhid_idle,
};
EXPORT_SYMBOL_GPL(usb_hid_driver);
static int usbhid_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev(intf);
struct usbhid_device *usbhid;
struct hid_device *hid;
unsigned int n, has_in = 0;
size_t len;
int ret;
dbg_hid("HID probe called for ifnum %d\n",
intf->altsetting->desc.bInterfaceNumber);
for (n = 0; n < interface->desc.bNumEndpoints; n++)
if (usb_endpoint_is_int_in(&interface->endpoint[n].desc))
has_in++;
if (!has_in) {
hid_err(intf, "couldn't find an input interrupt endpoint\n");
return -ENODEV;
}
hid = hid_allocate_device();
if (IS_ERR(hid))
return PTR_ERR(hid);
usb_set_intfdata(intf, hid);
hid->ll_driver = &usb_hid_driver;
hid->ff_init = hid_pidff_init;
#ifdef CONFIG_USB_HIDDEV
hid->hiddev_connect = hiddev_connect;
hid->hiddev_disconnect = hiddev_disconnect;
hid->hiddev_hid_event = hiddev_hid_event;
hid->hiddev_report_event = hiddev_report_event;
#endif
hid->dev.parent = &intf->dev;
hid->bus = BUS_USB;
hid->vendor = le16_to_cpu(dev->descriptor.idVendor);
hid->product = le16_to_cpu(dev->descriptor.idProduct);
hid->name[0] = 0;
hid->quirks = usbhid_lookup_quirk(hid->vendor, hid->product);
if (intf->cur_altsetting->desc.bInterfaceProtocol ==
USB_INTERFACE_PROTOCOL_MOUSE)
hid->type = HID_TYPE_USBMOUSE;
else if (intf->cur_altsetting->desc.bInterfaceProtocol == 0)
hid->type = HID_TYPE_USBNONE;
if (dev->manufacturer)
strlcpy(hid->name, dev->manufacturer, sizeof(hid->name));
if (dev->product) {
if (dev->manufacturer)
strlcat(hid->name, " ", sizeof(hid->name));
strlcat(hid->name, dev->product, sizeof(hid->name));
}
if (!strlen(hid->name))
snprintf(hid->name, sizeof(hid->name), "HID %04x:%04x",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
usb_make_path(dev, hid->phys, sizeof(hid->phys));
strlcat(hid->phys, "/input", sizeof(hid->phys));
len = strlen(hid->phys);
if (len < sizeof(hid->phys) - 1)
snprintf(hid->phys + len, sizeof(hid->phys) - len,
"%d", intf->altsetting[0].desc.bInterfaceNumber);
if (usb_string(dev, dev->descriptor.iSerialNumber, hid->uniq, 64) <= 0)
hid->uniq[0] = 0;
usbhid = kzalloc(sizeof(*usbhid), GFP_KERNEL);
if (usbhid == NULL) {
ret = -ENOMEM;
goto err;
}
hid->driver_data = usbhid;
usbhid->hid = hid;
usbhid->intf = intf;
usbhid->ifnum = interface->desc.bInterfaceNumber;
init_waitqueue_head(&usbhid->wait);
INIT_WORK(&usbhid->reset_work, hid_reset);
setup_timer(&usbhid->io_retry, hid_retry_timeout, (unsigned long) hid);
spin_lock_init(&usbhid->lock);
ret = hid_add_device(hid);
if (ret) {
if (ret != -ENODEV)
hid_err(intf, "can't add hid device: %d\n", ret);
goto err_free;
}
return 0;
err_free:
kfree(usbhid);
err:
hid_destroy_device(hid);
return ret;
}
static void usbhid_disconnect(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid;
if (WARN_ON(!hid))
return;
usbhid = hid->driver_data;
spin_lock_irq(&usbhid->lock); /* Sync with error and led handlers */
set_bit(HID_DISCONNECTED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
hid_destroy_device(hid);
kfree(usbhid);
}
static void hid_cancel_delayed_stuff(struct usbhid_device *usbhid)
{
del_timer_sync(&usbhid->io_retry);
cancel_work_sync(&usbhid->reset_work);
}
static void hid_cease_io(struct usbhid_device *usbhid)
{
del_timer_sync(&usbhid->io_retry);
usb_kill_urb(usbhid->urbin);
usb_kill_urb(usbhid->urbctrl);
usb_kill_urb(usbhid->urbout);
}
static void hid_restart_io(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
int clear_halt = test_bit(HID_CLEAR_HALT, &usbhid->iofl);
int reset_pending = test_bit(HID_RESET_PENDING, &usbhid->iofl);
spin_lock_irq(&usbhid->lock);
clear_bit(HID_SUSPENDED, &usbhid->iofl);
usbhid_mark_busy(usbhid);
if (clear_halt || reset_pending)
schedule_work(&usbhid->reset_work);
usbhid->retry_delay = 0;
spin_unlock_irq(&usbhid->lock);
if (reset_pending || !test_bit(HID_STARTED, &usbhid->iofl))
return;
if (!clear_halt) {
if (hid_start_in(hid) < 0)
hid_io_error(hid);
}
spin_lock_irq(&usbhid->lock);
if (usbhid->urbout && !test_bit(HID_OUT_RUNNING, &usbhid->iofl))
usbhid_restart_out_queue(usbhid);
if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
usbhid_restart_ctrl_queue(usbhid);
spin_unlock_irq(&usbhid->lock);
}
/* Treat USB reset pretty much the same as suspend/resume */
static int hid_pre_reset(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
spin_lock_irq(&usbhid->lock);
set_bit(HID_RESET_PENDING, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
hid_cease_io(usbhid);
return 0;
}
/* Same routine used for post_reset and reset_resume */
static int hid_post_reset(struct usb_interface *intf)
{
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
struct usb_host_interface *interface = intf->cur_altsetting;
int status;
char *rdesc;
/* Fetch and examine the HID report descriptor. If this
* has changed, then rebind. Since usbcore's check of the
* configuration descriptors passed, we already know that
* the size of the HID report descriptor has not changed.
*/
rdesc = kmalloc(hid->dev_rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
status = hid_get_class_descriptor(dev,
interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, hid->dev_rsize);
if (status < 0) {
dbg_hid("reading report descriptor failed (post_reset)\n");
kfree(rdesc);
return status;
}
status = memcmp(rdesc, hid->dev_rdesc, hid->dev_rsize);
kfree(rdesc);
if (status != 0) {
dbg_hid("report descriptor changed\n");
return -EPERM;
}
/* No need to do another reset or clear a halted endpoint */
spin_lock_irq(&usbhid->lock);
clear_bit(HID_RESET_PENDING, &usbhid->iofl);
clear_bit(HID_CLEAR_HALT, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
hid_set_idle(dev, intf->cur_altsetting->desc.bInterfaceNumber, 0, 0);
hid_restart_io(hid);
return 0;
}
#ifdef CONFIG_PM
static int hid_resume_common(struct hid_device *hid, bool driver_suspended)
{
int status = 0;
hid_restart_io(hid);
if (driver_suspended && hid->driver && hid->driver->resume)
status = hid->driver->resume(hid);
return status;
}
static int hid_suspend(struct usb_interface *intf, pm_message_t message)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
int status = 0;
bool driver_suspended = false;
unsigned int ledcount;
if (PMSG_IS_AUTO(message)) {
ledcount = hidinput_count_leds(hid);
spin_lock_irq(&usbhid->lock); /* Sync with error handler */
if (!test_bit(HID_RESET_PENDING, &usbhid->iofl)
&& !test_bit(HID_CLEAR_HALT, &usbhid->iofl)
&& !test_bit(HID_OUT_RUNNING, &usbhid->iofl)
&& !test_bit(HID_CTRL_RUNNING, &usbhid->iofl)
&& !test_bit(HID_KEYS_PRESSED, &usbhid->iofl)
&& (!ledcount || ignoreled))
{
set_bit(HID_SUSPENDED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
if (hid->driver && hid->driver->suspend) {
status = hid->driver->suspend(hid, message);
if (status < 0)
goto failed;
}
driver_suspended = true;
} else {
usbhid_mark_busy(usbhid);
spin_unlock_irq(&usbhid->lock);
return -EBUSY;
}
} else {
/* TODO: resume() might need to handle suspend failure */
if (hid->driver && hid->driver->suspend)
status = hid->driver->suspend(hid, message);
driver_suspended = true;
spin_lock_irq(&usbhid->lock);
set_bit(HID_SUSPENDED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
if (usbhid_wait_io(hid) < 0)
status = -EIO;
}
hid_cancel_delayed_stuff(usbhid);
hid_cease_io(usbhid);
if (PMSG_IS_AUTO(message) && test_bit(HID_KEYS_PRESSED, &usbhid->iofl)) {
/* lost race against keypresses */
status = -EBUSY;
goto failed;
}
dev_dbg(&intf->dev, "suspend\n");
return status;
failed:
hid_resume_common(hid, driver_suspended);
return status;
}
static int hid_resume(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata (intf);
int status;
status = hid_resume_common(hid, true);
dev_dbg(&intf->dev, "resume status %d\n", status);
return 0;
}
static int hid_reset_resume(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata(intf);
int status;
status = hid_post_reset(intf);
if (status >= 0 && hid->driver && hid->driver->reset_resume) {
int ret = hid->driver->reset_resume(hid);
if (ret < 0)
status = ret;
}
return status;
}
#endif /* CONFIG_PM */
static const struct usb_device_id hid_usb_ids[] = {
{ .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
.bInterfaceClass = USB_INTERFACE_CLASS_HID },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, hid_usb_ids);
static struct usb_driver hid_driver = {
.name = "usbhid",
.probe = usbhid_probe,
.disconnect = usbhid_disconnect,
#ifdef CONFIG_PM
.suspend = hid_suspend,
.resume = hid_resume,
.reset_resume = hid_reset_resume,
#endif
.pre_reset = hid_pre_reset,
.post_reset = hid_post_reset,
.id_table = hid_usb_ids,
.supports_autosuspend = 1,
};
struct usb_interface *usbhid_find_interface(int minor)
{
return usb_find_interface(&hid_driver, minor);
}
static int __init hid_init(void)
{
int retval = -ENOMEM;
retval = usbhid_quirks_init(quirks_param);
if (retval)
goto usbhid_quirks_init_fail;
retval = usb_register(&hid_driver);
if (retval)
goto usb_register_fail;
pr_info(KBUILD_MODNAME ": " DRIVER_DESC "\n");
return 0;
usb_register_fail:
usbhid_quirks_exit();
usbhid_quirks_init_fail:
return retval;
}
static void __exit hid_exit(void)
{
usb_deregister(&hid_driver);
usbhid_quirks_exit();
}
module_init(hid_init);
module_exit(hid_exit);
MODULE_AUTHOR("Andreas Gal");
MODULE_AUTHOR("Vojtech Pavlik");
MODULE_AUTHOR("Jiri Kosina");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2914_0 |
crossvul-cpp_data_good_5491_2 | /*
* 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 Decoder
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "jasper/jas_types.h"
#include "jasper/jas_fix.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_math.h"
#include "jasper/jas_stream.h"
#include "jasper/jas_debug.h"
#include "jpc_bs.h"
#include "jpc_dec.h"
#include "jpc_cs.h"
#include "jpc_mqdec.h"
#include "jpc_t2dec.h"
#include "jpc_t1cod.h"
#include "jpc_math.h"
/******************************************************************************\
*
\******************************************************************************/
long jpc_dec_lookahead(jas_stream_t *in);
static int jpc_getcommacode(jpc_bitstream_t *in);
static int jpc_getnumnewpasses(jpc_bitstream_t *in);
static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int lvlno,
int prcno, int lyrno);
/******************************************************************************\
* Code.
\******************************************************************************/
static int jpc_getcommacode(jpc_bitstream_t *in)
{
int n;
int v;
n = 0;
for (;;) {
if ((v = jpc_bitstream_getbit(in)) < 0) {
return -1;
}
if (jpc_bitstream_eof(in)) {
return -1;
}
if (!v) {
break;
}
++n;
}
return n;
}
static int jpc_getnumnewpasses(jpc_bitstream_t *in)
{
int n;
if ((n = jpc_bitstream_getbit(in)) > 0) {
if ((n = jpc_bitstream_getbit(in)) > 0) {
if ((n = jpc_bitstream_getbits(in, 2)) == 3) {
if ((n = jpc_bitstream_getbits(in, 5)) == 31) {
if ((n = jpc_bitstream_getbits(in, 7)) >= 0) {
n += 36 + 1;
}
} else if (n >= 0) {
n += 5 + 1;
}
} else if (n >= 0) {
n += 2 + 1;
}
} else if (!n) {
n += 2;
}
} else if (!n) {
++n;
}
return n;
}
static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,
int prcno, int lyrno)
{
jpc_bitstream_t *inb;
jpc_dec_tcomp_t *tcomp;
jpc_dec_rlvl_t *rlvl;
jpc_dec_band_t *band;
jpc_dec_cblk_t *cblk;
int n;
int m;
int i;
jpc_tagtreenode_t *leaf;
int included;
int ret;
int numnewpasses;
jpc_dec_seg_t *seg;
int len;
int present;
int savenumnewpasses;
int mycounter;
jpc_ms_t *ms;
jpc_dec_tile_t *tile;
jpc_dec_ccp_t *ccp;
jpc_dec_cp_t *cp;
int bandno;
jpc_dec_prc_t *prc;
int usedcblkcnt;
int cblkno;
uint_fast32_t bodylen;
bool discard;
int passno;
int maxpasses;
int hdrlen;
int hdroffstart;
int hdroffend;
/* Avoid compiler warning about possible use of uninitialized
variable. */
bodylen = 0;
discard = (lyrno >= dec->maxlyrs);
tile = dec->curtile;
cp = tile->cp;
ccp = &cp->ccps[compno];
/*
* Decode the packet header.
*/
/* Decode the SOP marker segment if present. */
if (cp->csty & JPC_COD_SOP) {
if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
if (!(ms = jpc_getms(in, dec->cstate))) {
return -1;
}
if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
jpc_ms_destroy(ms);
jas_eprintf("missing SOP marker segment\n");
return -1;
}
jpc_ms_destroy(ms);
}
}
hdroffstart = jas_stream_getrwcount(pkthdrstream);
if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) {
return -1;
}
if ((present = jpc_bitstream_getbit(inb)) < 0) {
return 1;
}
JAS_DBGLOG(10, ("\n", present));
JAS_DBGLOG(10, ("present=%d ", present));
/* Is the packet non-empty? */
if (present) {
/* The packet is non-empty. */
tcomp = &tile->tcomps[compno];
rlvl = &tcomp->rlvls[rlvlno];
bodylen = 0;
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (!band->data) {
continue;
}
prc = &band->prcs[prcno];
if (!prc->cblks) {
continue;
}
usedcblkcnt = 0;
for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
++cblkno, ++cblk) {
++usedcblkcnt;
if (!cblk->numpasses) {
leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);
if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {
return -1;
}
} else {
if ((included = jpc_bitstream_getbit(inb)) < 0) {
return -1;
}
}
JAS_DBGLOG(10, ("\n"));
JAS_DBGLOG(10, ("included=%d ", included));
if (!included) {
continue;
}
if (!cblk->numpasses) {
i = 1;
leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);
for (;;) {
if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {
return -1;
}
if (ret) {
break;
}
++i;
}
cblk->numimsbs = i - 1;
cblk->firstpassno = cblk->numimsbs * 3;
}
if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {
return -1;
}
JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
seg = cblk->curseg;
savenumnewpasses = numnewpasses;
mycounter = 0;
if (numnewpasses > 0) {
if ((m = jpc_getcommacode(inb)) < 0) {
return -1;
}
cblk->numlenbits += m;
JAS_DBGLOG(10, ("increment=%d ", m));
while (numnewpasses > 0) {
passno = cblk->firstpassno + cblk->numpasses + mycounter;
/* XXX - the maxpasses is not set precisely but this doesn't matter... */
maxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);
if (!discard && !seg) {
if (!(seg = jpc_seg_alloc())) {
return -1;
}
jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);
if (!cblk->curseg) {
cblk->curseg = seg;
}
seg->passno = passno;
seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);
seg->maxpasses = maxpasses;
}
n = JAS_MIN(numnewpasses, maxpasses);
mycounter += n;
numnewpasses -= n;
if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {
return -1;
}
JAS_DBGLOG(10, ("len=%d ", len));
if (!discard) {
seg->lyrno = lyrno;
seg->numpasses += n;
seg->cnt = len;
seg = seg->next;
}
bodylen += len;
}
}
cblk->numpasses += savenumnewpasses;
}
}
jpc_bitstream_inalign(inb, 0, 0);
} else {
if (jpc_bitstream_inalign(inb, 0x7f, 0)) {
jas_eprintf("alignment failed\n");
return -1;
}
}
jpc_bitstream_close(inb);
hdroffend = jas_stream_getrwcount(pkthdrstream);
hdrlen = hdroffend - hdroffstart;
if (jas_getdbglevel() >= 5) {
jas_eprintf("hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen,
(unsigned long) bodylen);
}
if (cp->csty & JPC_COD_EPH) {
if (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {
if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {
jas_eprintf("cannot get (EPH) marker segment\n");
return -1;
}
if (jpc_ms_gettype(ms) != JPC_MS_EPH) {
jpc_ms_destroy(ms);
jas_eprintf("missing EPH marker segment\n");
return -1;
}
jpc_ms_destroy(ms);
}
}
/* decode the packet body. */
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
}
if (!discard) {
tcomp = &tile->tcomps[compno];
rlvl = &tcomp->rlvls[rlvlno];
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (!band->data) {
continue;
}
prc = &band->prcs[prcno];
if (!prc->cblks) {
continue;
}
for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
++cblkno, ++cblk) {
seg = cblk->curseg;
while (seg) {
if (!seg->stream) {
if (!(seg->stream = jas_stream_memopen(0, 0))) {
return -1;
}
}
#if 0
jas_eprintf("lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);
#endif
if (seg->cnt > 0) {
if (jpc_getdata(in, seg->stream, seg->cnt) < 0) {
return -1;
}
seg->cnt = 0;
}
if (seg->numpasses >= seg->maxpasses) {
cblk->curseg = seg->next;
}
seg = seg->next;
}
}
}
} else {
if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {
return -1;
}
}
return 0;
}
/********************************************************************************************/
/********************************************************************************************/
int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
{
jpc_dec_tile_t *tile;
jpc_pi_t *pi;
int ret;
tile = dec->curtile;
pi = tile->pi;
for (;;) {
if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
switch (jpc_dec_lookahead(in)) {
case JPC_MS_EOC:
case JPC_MS_SOT:
return 0;
break;
case JPC_MS_SOP:
case JPC_MS_EPH:
case 0:
break;
default:
return -1;
break;
}
}
if ((ret = jpc_pi_next(pi))) {
return ret;
}
if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
jas_eprintf("warning: stopping decode prematurely as requested\n");
return 0;
}
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
"rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
}
if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
return -1;
}
++dec->numpkts;
}
return 0;
}
jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_pi_t *pi;
int compno;
jpc_picomp_t *picomp;
jpc_pirlvl_t *pirlvl;
jpc_dec_tcomp_t *tcomp;
int rlvlno;
jpc_dec_rlvl_t *rlvl;
int prcno;
int *prclyrno;
jpc_dec_cmpt_t *cmpt;
if (!(pi = jpc_pi_create0())) {
return 0;
}
pi->numcomps = dec->numcomps;
if (!(pi->picomps = jas_alloc2(pi->numcomps, sizeof(jpc_picomp_t)))) {
jpc_pi_destroy(pi);
return 0;
}
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno,
++picomp) {
picomp->pirlvls = 0;
}
for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps;
compno < pi->numcomps; ++compno, ++tcomp, ++picomp) {
picomp->numrlvls = tcomp->numrlvls;
if (!(picomp->pirlvls = jas_alloc2(picomp->numrlvls,
sizeof(jpc_pirlvl_t)))) {
jpc_pi_destroy(pi);
return 0;
}
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
pirlvl->prclyrnos = 0;
}
for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
/* XXX sizeof(long) should be sizeof different type */
pirlvl->numprcs = rlvl->numprcs;
if (!(pirlvl->prclyrnos = jas_alloc2(pirlvl->numprcs,
sizeof(long)))) {
jpc_pi_destroy(pi);
return 0;
}
}
}
pi->maxrlvls = 0;
for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt =
dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp,
++cmpt) {
picomp->hsamp = cmpt->hstep;
picomp->vsamp = cmpt->vstep;
for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
pirlvl->prcwidthexpn = rlvl->prcwidthexpn;
pirlvl->prcheightexpn = rlvl->prcheightexpn;
for (prcno = 0, prclyrno = pirlvl->prclyrnos;
prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
*prclyrno = 0;
}
pirlvl->numhprcs = rlvl->numhprcs;
}
if (pi->maxrlvls < tcomp->numrlvls) {
pi->maxrlvls = tcomp->numrlvls;
}
}
pi->numlyrs = tile->cp->numlyrs;
pi->xstart = tile->xstart;
pi->ystart = tile->ystart;
pi->xend = tile->xend;
pi->yend = tile->yend;
pi->picomp = 0;
pi->pirlvl = 0;
pi->x = 0;
pi->y = 0;
pi->compno = 0;
pi->rlvlno = 0;
pi->prcno = 0;
pi->lyrno = 0;
pi->xstep = 0;
pi->ystep = 0;
pi->pchgno = -1;
pi->defaultpchg.prgord = tile->cp->prgord;
pi->defaultpchg.compnostart = 0;
pi->defaultpchg.compnoend = pi->numcomps;
pi->defaultpchg.rlvlnostart = 0;
pi->defaultpchg.rlvlnoend = pi->maxrlvls;
pi->defaultpchg.lyrnoend = pi->numlyrs;
pi->pchg = 0;
pi->valid = 0;
return pi;
}
long jpc_dec_lookahead(jas_stream_t *in)
{
uint_fast16_t x;
if (jpc_getuint16(in, &x)) {
return -1;
}
if (jas_stream_ungetc(in, x & 0xff) == EOF ||
jas_stream_ungetc(in, x >> 8) == EOF) {
return -1;
}
if (x >= JPC_MS_INMIN && x <= JPC_MS_INMAX) {
return x;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5491_2 |
crossvul-cpp_data_bad_351_5 | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Initially written by Weitao Sun (weitao@ftsafe.com) 2008 */
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static struct sc_atr_table entersafe_atrs[] = {
{
"3b:0f:00:65:46:53:05:19:05:71:df:00:00:00:00:00:00",
"ff:ff:ff:ff:ff:ff:ff:00:ff:ff:ff:00:00:00:00:00:00",
"ePass3000", SC_CARD_TYPE_ENTERSAFE_3K, 0, NULL },
{
"3b:9f:95:81:31:fe:9f:00:65:46:53:05:30:06:71:df:00:00:00:80:6a:82:5e",
"FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00:00",
"FTCOS/PK-01C", SC_CARD_TYPE_ENTERSAFE_FTCOS_PK_01C, 0, NULL },
{
"3b:fc:18:00:00:81:31:80:45:90:67:46:4a:00:64:18:14:00:00:00:00:02",
"ff:00:00:00:00:00:00:00:00:ff:ff:ff:ff:00:00:00:00:ff:ff:ff:ff:00",
"EJAVA/PK-01C", SC_CARD_TYPE_ENTERSAFE_EJAVA_PK_01C, 0, NULL },
{
"3b:7c:18:00:00:90:67:46:4a:20:28:8c:58:00:00:00:00",
"ff:00:00:00:00:ff:ff:ff:ff:00:00:00:00:ff:ff:ff:ff",
"EJAVA/PK-01C-T0",SC_CARD_TYPE_ENTERSAFE_EJAVA_PK_01C_T0,0,NULL},
{
"3B:FC:18:00:00:81:31:80:45:90:67:46:4A:21:28:8C:58:00:00:00:00:B7",
"ff:00:00:00:00:00:00:00:00:ff:ff:ff:ff:00:00:00:00:ff:ff:ff:ff:00",
"EJAVA/H10CR/PK-01C-T1",SC_CARD_TYPE_ENTERSAFE_EJAVA_H10CR_PK_01C_T1,0,NULL},
{
"3B:FC:18:00:00:81:31:80:45:90:67:46:4A:20:25:c3:30:00:00:00:00",
"ff:00:00:00:00:00:00:00:00:ff:ff:ff:ff:00:00:00:00:00:00:00:00",
"EJAVA/D11CR/PK-01C-T1",SC_CARD_TYPE_ENTERSAFE_EJAVA_D11CR_PK_01C_T1,0,NULL},
{
"3B:FC:18:00:00:81:31:80:45:90:67:46:4A:00:6A:04:24:00:00:00:00:20",
"ff:00:00:00:00:00:00:00:00:ff:ff:ff:ff:00:00:00:00:ff:ff:ff:ff:00",
"EJAVA/C21C/PK-01C-T1",SC_CARD_TYPE_ENTERSAFE_EJAVA_C21C_PK_01C_T1,0,NULL},
{
"3B:FC:18:00:00:81:31:80:45:90:67:46:4A:00:68:08:04:00:00:00:00:0E",
"ff:00:00:00:00:00:00:00:00:ff:ff:ff:ff:00:00:00:00:ff:ff:ff:ff:00",
"EJAVA/A22CR/PK-01C-T1",SC_CARD_TYPE_ENTERSAFE_EJAVA_A22CR_PK_01C_T1,0,NULL},
{
"3B:FC:18:00:00:81:31:80:45:90:67:46:4A:10:27:61:30:00:00:00:00:0C",
"ff:00:00:00:00:00:00:00:00:ff:ff:ff:ff:00:00:00:00:ff:ff:ff:ff:00",
"EJAVA/A40CR/PK-01C-T1",SC_CARD_TYPE_ENTERSAFE_EJAVA_A40CR_PK_01C_T1,0,NULL},
{
"3b:fc:18:00:00:81:31:80:45:90:67:46:4a:00:68:08:06:00:00:00:00:0c",
"FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:00:FF:FF:FF:FF:FF:FF:00:00:00",
"FTCOS/PK-01C", SC_CARD_TYPE_ENTERSAFE_FTCOS_PK_01C, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_card_operations entersafe_ops;
static struct sc_card_operations *iso_ops = NULL;
static struct sc_card_driver entersafe_drv = {
"entersafe",
"entersafe",
&entersafe_ops,
NULL, 0, NULL
};
static u8 trans_code_3k[] =
{
0x01,0x02,0x03,0x04,
0x05,0x06,0x07,0x08,
};
static u8 trans_code_ftcos_pk_01c[] =
{
0x92,0x34,0x2E,0xEF,
0x23,0x40,0x4F,0xD1,
};
static u8 init_key[] =
{
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16,
};
static u8 key_maintain[] =
{
0x12, 0x34, 0x56, 0x78,
0x21, 0x43, 0x65, 0x87,
0x11, 0x22, 0xaa, 0xbb,
0x33, 0x44, 0xcd, 0xef
};
static void entersafe_reverse_buffer(u8* buff,size_t size)
{
u8 t;
u8 * end=buff+size-1;
while(buff<end)
{
t = *buff;
*buff = *end;
*end=t;
++buff;
--end;
}
}
static int entersafe_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out);
/* the entersafe part */
static int entersafe_match_card(sc_card_t *card)
{
int i;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
i = _sc_match_atr(card, entersafe_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int entersafe_init(sc_card_t *card)
{
unsigned int flags;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
card->name = "entersafe";
card->cla = 0x00;
card->drv_data = NULL;
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);
card->caps = SC_CARD_CAP_RNG;
/* we need read_binary&friends with max 224 bytes per read */
card->max_send_size = 224;
card->max_recv_size = 224;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_gen_random(sc_card_t *card,u8 *buff,size_t size)
{
int r=SC_SUCCESS;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]={0};
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card,&apdu,SC_APDU_CASE_2_SHORT,0x84,0x00,0x00);
apdu.resp=rbuf;
apdu.le=size;
apdu.resplen=sizeof(rbuf);
r=sc_transmit_apdu(card,&apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "entersafe gen random failed");
if(apdu.resplen!=size)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL,SC_ERROR_INTERNAL);
memcpy(buff,rbuf,size);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL,r);
}
static int entersafe_cipher_apdu(sc_card_t *card, sc_apdu_t *apdu,
u8 *key, size_t keylen,
u8 *buff, size_t buffsize)
{
EVP_CIPHER_CTX * ctx = NULL;
u8 iv[8]={0};
int len;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(card);
assert(apdu);
assert(key);
assert(buff);
/* padding as 0x80 0x00 0x00...... */
memset(buff,0,buffsize);
buff[0]=apdu->lc;
memcpy(buff+1,apdu->data,apdu->lc);
buff[apdu->lc+1]=0x80;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
EVP_CIPHER_CTX_set_padding(ctx,0);
if(keylen == 8)
EVP_EncryptInit_ex(ctx, EVP_des_ecb(), NULL, key, iv);
else if (keylen == 16)
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, key, iv);
else
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
len = apdu->lc;
if(!EVP_EncryptUpdate(ctx, buff, &len, buff, buffsize)){
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "entersafe encryption error.");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
}
apdu->lc = len;
EVP_CIPHER_CTX_free(ctx);
if(apdu->lc!=buffsize)
{
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "entersafe build cipher apdu failed.");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INTERNAL);
}
apdu->data=buff;
apdu->datalen=apdu->lc;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_SUCCESS);
}
static int entersafe_mac_apdu(sc_card_t *card, sc_apdu_t *apdu,
u8 * key,size_t keylen,
u8 * buff,size_t buffsize)
{
int r;
u8 iv[8];
u8 *tmp=0,*tmp_rounded=NULL;
size_t tmpsize=0,tmpsize_rounded=0;
int outl=0;
EVP_CIPHER_CTX * ctx = NULL;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(card);
assert(apdu);
assert(key);
assert(buff);
if(apdu->cse != SC_APDU_CASE_3_SHORT)
return SC_ERROR_INTERNAL;
if(keylen!=8 && keylen!=16)
return SC_ERROR_INTERNAL;
r=entersafe_gen_random(card,iv,sizeof(iv));
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL,r,"entersafe gen random failed");
/* encode the APDU in the buffer */
if ((r=sc_apdu_get_octets(card->ctx, apdu, &tmp, &tmpsize,SC_PROTO_RAW)) != SC_SUCCESS)
goto out;
/* round to 8 */
tmpsize_rounded=(tmpsize/8+1)*8;
tmp_rounded = malloc(tmpsize_rounded);
if (tmp_rounded == NULL)
{
r = SC_ERROR_OUT_OF_MEMORY;
goto out;
}
/*build content and padded buffer by 0x80 0x00 0x00..... */
memset(tmp_rounded,0,tmpsize_rounded);
memcpy(tmp_rounded,tmp,tmpsize);
tmp_rounded[4]+=4;
tmp_rounded[tmpsize]=0x80;
/* block_size-1 blocks*/
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto out;
}
EVP_CIPHER_CTX_set_padding(ctx,0);
EVP_EncryptInit_ex(ctx, EVP_des_cbc(), NULL, key, iv);
if(tmpsize_rounded>8){
if(!EVP_EncryptUpdate(ctx,tmp_rounded,&outl,tmp_rounded,tmpsize_rounded-8)){
r = SC_ERROR_INTERNAL;
goto out;
}
}
/* last block */
if(keylen==8)
{
if(!EVP_EncryptUpdate(ctx,tmp_rounded+outl,&outl,tmp_rounded+outl,8)){
r = SC_ERROR_INTERNAL;
goto out;
}
}
else
{
EVP_EncryptInit_ex(ctx, EVP_des_ede_cbc(), NULL, key,tmp_rounded+outl-8);
if(!EVP_EncryptUpdate(ctx,tmp_rounded+outl,&outl,tmp_rounded+outl,8)){
r = SC_ERROR_INTERNAL;
goto out;
}
}
memcpy(buff,apdu->data,apdu->lc);
/* use first 4 bytes of last block as mac value*/
memcpy(buff+apdu->lc,tmp_rounded+tmpsize_rounded-8,4);
apdu->data=buff;
apdu->lc+=4;
apdu->datalen=apdu->lc;
out:
if(tmp)
free(tmp);
if(tmp_rounded)
free(tmp_rounded);
if (ctx)
EVP_CIPHER_CTX_free(ctx);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int entersafe_transmit_apdu(sc_card_t *card, sc_apdu_t *apdu,
u8 * key, size_t keylen,
int cipher,int mac)
{
u8 *cipher_data=0,*mac_data=0;
size_t cipher_data_size,mac_data_size;
int blocks;
int r=SC_SUCCESS;
u8 *sbuf=NULL;
size_t ssize=0;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(card);
assert(apdu);
if((cipher||mac) && (!key||(keylen!=8 && keylen!=16)))
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
r = sc_apdu_get_octets(card->ctx, apdu, &sbuf, &ssize, SC_PROTO_RAW);
if (r == SC_SUCCESS)
sc_apdu_log(card->ctx, SC_LOG_DEBUG_VERBOSE, sbuf, ssize, 1);
if(sbuf)
free(sbuf);
if(cipher)
{
blocks=(apdu->lc+2)/8+1;
cipher_data_size=blocks*8;
cipher_data=malloc(cipher_data_size);
if(!cipher_data)
{
r = SC_ERROR_OUT_OF_MEMORY;
goto out;
}
if((r = entersafe_cipher_apdu(card,apdu,key,keylen,cipher_data,cipher_data_size))<0)
goto out;
}
if(mac)
{
mac_data_size=apdu->lc+4;
mac_data=malloc(mac_data_size);
if(!mac_data)
{
r = SC_ERROR_OUT_OF_MEMORY;
goto out;
}
r = entersafe_mac_apdu(card,apdu,key,keylen,mac_data,mac_data_size);
if(r < 0)
goto out;
}
r = sc_transmit_apdu(card,apdu);
out:
if(cipher_data)
free(cipher_data);
if(mac_data)
free(mac_data);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int entersafe_read_binary(sc_card_t *card,
unsigned int idx, u8 *buf, size_t count,
unsigned long flags)
{
sc_apdu_t apdu;
u8 recvbuf[SC_MAX_APDU_BUFFER_SIZE];
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(count <= card->max_recv_size);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0,
(idx >> 8) & 0xFF, idx & 0xFF);
apdu.cla=idx > 0x7fff ? 0x80:0x00;
apdu.le = count;
apdu.resplen = count;
apdu.resp = recvbuf;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.resplen == 0)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
memcpy(buf, recvbuf, apdu.resplen);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, apdu.resplen);
}
static int entersafe_update_binary(sc_card_t *card,
unsigned int idx, const u8 *buf,
size_t count, unsigned long flags)
{
sc_apdu_t apdu;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(count <= card->max_send_size);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD6,
(idx >> 8) & 0xFF, idx & 0xFF);
apdu.cla=idx > 0x7fff ? 0x80:0x00;
apdu.lc = count;
apdu.datalen = count;
apdu.data = buf;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),
"Card returned error");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, count);
}
static int entersafe_process_fci(struct sc_card *card, struct sc_file *file,
const u8 *buf, size_t buflen)
{
int r;
assert(file);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = iso_ops->process_fci(card,file,buf,buflen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Process fci failed");
if(file->namelen)
{
file->type = SC_FILE_TYPE_DF;
file->ef_structure = SC_FILE_EF_UNKNOWN;
}
else
{
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = SC_FILE_EF_TRANSPARENT;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int entersafe_select_fid(sc_card_t *card,
unsigned int id_hi, unsigned int id_lo,
sc_file_t **file_out)
{
int r;
sc_file_t *file = NULL;
sc_path_t path;
memset(&path, 0, sizeof(sc_path_t));
path.type=SC_PATH_TYPE_FILE_ID;
path.value[0]=id_hi;
path.value[1]=id_lo;
path.len=2;
r = iso_ops->select_file(card,&path,&file);
if (r < 0)
sc_file_free(file);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
/* update cache */
if (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;
else
sc_file_free(file);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_SUCCESS);
}
static int entersafe_select_aid(sc_card_t *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)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
}
else
{
r = iso_ops->select_file(card,in_path,file_out);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, 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;
assert(file);
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;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int entersafe_select_path(sc_card_t *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)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
/* if pathlen == 6 then the first FID must be MF (== 3F00) */
if (pathlen == 6 && ( path[0] != 0x3f || path[1] != 0x00 ))
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, 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 entersafe_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 = entersafe_select_fid(card, path[bMatch], path[bMatch+1], NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "SELECT FILE (DF-ID) failed");
memset(&new_path, 0, sizeof(sc_path_t));
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 entersafe_select_file(card, &new_path, file_out);
}
else /* if (bMatch - pathlen == 0) */
{
/* done: we are already in the
* requested directory */
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"cache hit\n");
/* copy file info (if necessary) */
if (file_out) {
sc_file_t *file = sc_file_new();
if (!file)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, 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 = entersafe_select_fid(card, path[i], path[i+1], NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "SELECT FILE (DF-ID) failed");
}
return entersafe_select_fid(card, path[pathlen-2], path[pathlen-1], file_out);
}
}
static int entersafe_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
int r;
char pbuf[SC_MAX_PATH_STRING_SIZE];
assert(card);
assert(in_path);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
r = sc_path_print(pbuf, sizeof(pbuf), &card->cache.current_path);
if (r != SC_SUCCESS)
pbuf[0] = '\0';
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"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)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_INVALID_ARGUMENTS);
return entersafe_select_fid(card,in_path->value[0],in_path->value[1], file_out);
case SC_PATH_TYPE_DF_NAME:
return entersafe_select_aid(card,in_path,file_out);
case SC_PATH_TYPE_PATH:
return entersafe_select_path(card,in_path->value,in_path->len,file_out);
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
}
static int entersafe_create_mf(sc_card_t *card, sc_entersafe_create_data * data)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(data->data.df.init_key, init_key, sizeof(init_key));
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xE0,0x00,0x00);
apdu.cla=0x84;
apdu.data=(u8*)&data->data.df;
apdu.datalen=apdu.lc=sizeof(data->data.df);
switch(card->type)
{
case SC_CARD_TYPE_ENTERSAFE_3K:
{
r = entersafe_transmit_apdu(card, &apdu,trans_code_3k,sizeof(trans_code_3k),0,1);
}break;
case SC_CARD_TYPE_ENTERSAFE_FTCOS_PK_01C:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_PK_01C:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_PK_01C_T0:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_H10CR_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_D11CR_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_C21C_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_A22CR_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_A40CR_PK_01C_T1:
{
r = entersafe_transmit_apdu(card, &apdu,trans_code_ftcos_pk_01c,sizeof(trans_code_ftcos_pk_01c),0,1);
}break;
default:
{
r = SC_ERROR_INTERNAL;
}break;
}
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int entersafe_create_df(sc_card_t *card, sc_entersafe_create_data * data)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
memcpy(data->data.df.init_key, init_key, sizeof(init_key));
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xE0,0x01,0x00);
apdu.cla=0x84;
apdu.data=(u8*)&data->data.df;
apdu.lc=apdu.datalen=sizeof(data->data.df);
r = entersafe_transmit_apdu(card, &apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int entersafe_create_ef(sc_card_t *card, sc_entersafe_create_data * data)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x02, 0x00);
apdu.cla = 0x84;
apdu.data = (u8*)&data->data.ef;
apdu.lc = apdu.datalen = sizeof(data->data.ef);
r = entersafe_transmit_apdu(card, &apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static u8 process_acl_entry(sc_file_t *in, unsigned int method, unsigned int in_def)
{
u8 def = (u8)in_def;
const sc_acl_entry_t *entry = sc_file_get_acl_entry(in, method);
if (!entry)
{
return def;
}
else if (entry->method & SC_AC_CHV)
{
unsigned int key_ref = entry->key_ref;
if (key_ref == SC_AC_KEY_REF_NONE)
return def;
else
return ENTERSAFE_AC_ALWAYS&0x04;
}
else if (entry->method & SC_AC_NEVER)
{
return ENTERSAFE_AC_NEVER;
}
else
{
return def;
}
}
static int entersafe_create_file(sc_card_t *card, sc_file_t *file)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (file->type == SC_FILE_TYPE_WORKING_EF) {
sc_entersafe_create_data data;
memset(&data,0,sizeof(data));
data.data.ef.file_id[0] = (file->id>>8)&0xFF;
data.data.ef.file_id[1] = file->id&0xFF;
data.data.ef.size[0] = (file->size>>8)&0xFF;
data.data.ef.size[1] = file->size&0xFF;
memset(data.data.ef.ac,ENTERSAFE_AC_ALWAYS,sizeof(data.data.ef.ac));
data.data.ef.ac[0] = process_acl_entry(file,SC_AC_OP_READ,ENTERSAFE_AC_ALWAYS);
data.data.ef.ac[1] = process_acl_entry(file,SC_AC_OP_UPDATE,ENTERSAFE_AC_ALWAYS);
return entersafe_create_ef(card, &data);
} else
return SC_ERROR_INVALID_ARGUMENTS;
}
static int entersafe_internal_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
u8 ** data,size_t* size)
{
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 *p=sbuf;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(card != NULL && env != NULL);
switch (env->operation) {
case SC_SEC_OPERATION_DECIPHER:
case SC_SEC_OPERATION_SIGN:
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0);
apdu.p1 = 0x41;
apdu.p2 = 0xB8;
*p++ = 0x80;
*p++ = 0x01;
*p++ = 0x80;
*p++ = 0x83;
*p++ = 0x02;
*p++ = env->key_ref[0];
*p++ = 0x22;
if(*size>1024/8)
{
if(*size == 2048/8)
{
*p++ = 0x89;
*p++ = 0x40;
memcpy(p,*data,0x40);
p+=0x40;
*data+=0x40;
*size-=0x40;
}
else
{
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
}
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.le = 0;
apdu.lc = apdu.datalen = p - sbuf;
apdu.data = sbuf;
apdu.resplen = 0;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
/**
* We don't really set the security environment,but cache it.It will be set when
* security operation is performed later.Because we may transport partial of
* the sign/decipher data within the security environment apdu.
*/
static int entersafe_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
assert(card);
assert(env);
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if(card->drv_data){
free(card->drv_data);
card->drv_data=0;
}
card->drv_data = calloc(1,sizeof(*env));
if(!card->drv_data)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY);
memcpy(card->drv_data,env,sizeof(*env));
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_SUCCESS);
}
static int entersafe_restore_security_env(sc_card_t *card, int se_num)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
return SC_SUCCESS;
}
static int entersafe_compute_with_prkey(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
int r;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8* p=sbuf;
size_t size = datalen;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if(!data)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_INVALID_ARGUMENTS);
memcpy(p,data,size);
if(!card->drv_data)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_INTERNAL);
r = entersafe_internal_set_security_env(card,card->drv_data,&p,&size);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "internal set security env failed");
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x86,0x80);
apdu.data=p;
apdu.lc = size;
apdu.datalen = size;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
size_t len = apdu.resplen > outlen ? outlen : apdu.resplen;
memcpy(out, apdu.resp, len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static int entersafe_compute_signature(sc_card_t *card,
const u8 * data, size_t datalen,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
return entersafe_compute_with_prkey(card,data,datalen,out,outlen);
}
static int entersafe_decipher(sc_card_t *card,
const u8 * crgram, size_t crgram_len,
u8 * out, size_t outlen)
{
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
return entersafe_compute_with_prkey(card,crgram,crgram_len,out,outlen);
}
static void entersafe_init_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 entersafe_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data,
int *tries_left)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
entersafe_init_pin_info(&data->pin1,0);
entersafe_init_pin_info(&data->pin2,1);
data->flags |= SC_PIN_CMD_NEED_PADDING;
if(data->cmd!=SC_PIN_CMD_UNBLOCK)
{
r = iso_ops->pin_cmd(card,data,tries_left);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Verify rv:%i", r);
}
else
{
{/*verify*/
sc_apdu_t apdu;
u8 sbuf[0x10]={0};
memcpy(sbuf,data->pin1.data,data->pin1.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT,0x20,0x00,data->pin_reference+1);
apdu.lc = apdu.datalen = sizeof(sbuf);
apdu.data = sbuf;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
{/*change*/
sc_apdu_t apdu;
u8 sbuf[0x12]={0};
sbuf[0] = 0x33;
sbuf[1] = 0x00;
memcpy(sbuf+2,data->pin2.data,data->pin2.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT,0xF4,0x0B,data->pin_reference);
apdu.cla = 0x84;
apdu.lc = apdu.datalen = sizeof(sbuf);
apdu.data = sbuf;
r = entersafe_transmit_apdu(card, &apdu,key_maintain,sizeof(key_maintain),1,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int entersafe_erase_card(sc_card_t *card)
{
int r;
u8 sbuf[2];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
sbuf[0] = 0x3f;
sbuf[1] = 0x00;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
sc_invalidate_cache(card);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xEE, 0x00, 0x00);
apdu.cla=0x84;
apdu.lc=2;
apdu.datalen=2;
apdu.data=sbuf;
switch(card->type)
{
case SC_CARD_TYPE_ENTERSAFE_3K:
{
r = entersafe_transmit_apdu(card, &apdu,trans_code_3k,sizeof(trans_code_3k),0,1);
}break;
case SC_CARD_TYPE_ENTERSAFE_FTCOS_PK_01C:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_PK_01C:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_PK_01C_T0:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_H10CR_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_D11CR_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_C21C_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_A22CR_PK_01C_T1:
case SC_CARD_TYPE_ENTERSAFE_EJAVA_A40CR_PK_01C_T1:
{
r = entersafe_transmit_apdu(card, &apdu,trans_code_ftcos_pk_01c,sizeof(trans_code_ftcos_pk_01c),0,1);
}break;
default:
{
r = SC_ERROR_INTERNAL;
}break;
}
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
static void entersafe_encode_bignum(u8 tag,sc_pkcs15_bignum_t bignum,u8** ptr)
{
u8 *p=*ptr;
*p++=tag;
if(bignum.len<128)
{
*p++=(u8)bignum.len;
}
else
{
u8 bytes=1;
size_t len=bignum.len;
while(len)
{
len=len>>8;
++bytes;
}
bytes&=0x0F;
*p++=0x80|bytes;
while(bytes)
{
*p++=bignum.len>>((bytes-1)*8);
--bytes;
}
}
memcpy(p,bignum.data,bignum.len);
entersafe_reverse_buffer(p,bignum.len);
p+=bignum.len;
*ptr = p;
}
static int entersafe_write_small_rsa_key(sc_card_t *card,u8 key_id,struct sc_pkcs15_prkey_rsa *rsa)
{
sc_apdu_t apdu;
u8 sbuff[SC_MAX_APDU_BUFFER_SIZE];
int r;
u8 *p=sbuff;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
{/* write prkey */
*p++=0x00; /* EC */
*p++=0x00; /* ver */
entersafe_encode_bignum('E',rsa->exponent,&p);
entersafe_encode_bignum('D',rsa->d,&p);
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF4,0x22,key_id);
apdu.cla=0x84;
apdu.data=sbuff;
apdu.lc=apdu.datalen=p-sbuff;
r=entersafe_transmit_apdu(card,&apdu,key_maintain,sizeof(key_maintain),1,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write prkey failed");
}
p=sbuff;
{/* write pukey */
*p++=0x00; /* EC */
*p++=0x00; /* ver */
entersafe_encode_bignum('E',rsa->exponent,&p);
entersafe_encode_bignum('N',rsa->modulus,&p);
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF4,0x2A,key_id);
apdu.cla=0x84;
apdu.data=sbuff;
apdu.lc=apdu.datalen=p-sbuff;
r=entersafe_transmit_apdu(card,&apdu,key_maintain,sizeof(key_maintain),1,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write pukey failed");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_write_rsa_key_factor(sc_card_t *card,
u8 key_id,u8 usage,
u8 factor,
sc_pkcs15_bignum_t data)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
{/* MSE */
u8 sbuff[4];
sbuff[0]=0x84;
sbuff[1]=0x02;
sbuff[2]=key_id;
sbuff[3]=usage;
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0x22,0x01,0xB8);
apdu.data=sbuff;
apdu.lc=apdu.datalen=4;
r=entersafe_transmit_apdu(card,&apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write prkey factor failed(MSE)");
}
{/* Write 'x'; */
u8 sbuff[SC_MAX_APDU_BUFFER_SIZE];
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0x46,factor,0x00);
memcpy(sbuff,data.data,data.len);
entersafe_reverse_buffer(sbuff,data.len);
/*
* PK01C and PK13C smart card only support 1024 or 2048bit key .
* Size of exponent1 exponent2 coefficient of RSA private key keep the same as size of prime1
* So check factor is padded with zero or not
*/
switch(factor){
case 0x3:
case 0x4:
case 0x5:
{
if( data.len > 32 && data.len < 64 )
{
for(r = data.len ; r < 64 ; r ++)
sbuff[r] = 0;
data.len = 64;
}
else if( data.len > 64 && data.len < 128 )
{
for(r = data.len ; r < 128 ; r ++)
sbuff[r] = 0;
data.len = 128;
}
}
break;
default:
break;
}
apdu.data=sbuff;
apdu.lc=apdu.datalen=data.len;
r = entersafe_transmit_apdu(card,&apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write prkey factor failed");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_write_large_rsa_key(sc_card_t *card,u8 key_id,struct sc_pkcs15_prkey_rsa *rsa)
{
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
{/* write prkey */
r = entersafe_write_rsa_key_factor(card,key_id,0x22,0x01,rsa->p);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "write p failed");
r = entersafe_write_rsa_key_factor(card,key_id,0x22,0x02,rsa->q);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "write q failed");
r = entersafe_write_rsa_key_factor(card,key_id,0x22,0x03,rsa->dmp1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "write dmp1 failed");
r = entersafe_write_rsa_key_factor(card,key_id,0x22,0x04,rsa->dmq1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "write dmq1 failed");
r = entersafe_write_rsa_key_factor(card,key_id,0x22,0x05,rsa->iqmp);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "write iqmp failed");
}
{/* write pukey */
u8 sbuff[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
/* first 64(0x40) bytes of N */
sbuff[0]=0x83;
sbuff[1]=0x02;
sbuff[2]=key_id;
sbuff[3]=0x2A;
sbuff[4]=0x89;
sbuff[5]=0x40;
memcpy(sbuff+6,rsa->modulus.data,0x40);
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0x22,0x01,0xB8);
apdu.data=sbuff;
apdu.lc=apdu.datalen=0x46;
r=entersafe_transmit_apdu(card,&apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write pukey N(1) failed");
/* left 192(0xC0) bytes of N */
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0x46,0x0B,0x00);
apdu.data=rsa->modulus.data+0x40;
apdu.lc=apdu.datalen=0xC0;
r=entersafe_transmit_apdu(card,&apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write pukey N(2) failed");
/* E */
r = entersafe_write_rsa_key_factor(card,key_id,0x2A,0x0D,rsa->exponent);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "write exponent failed");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_write_symmetric_key(sc_card_t *card,
u8 key_id,u8 usage,
u8 EC,u8 ver,
u8 *data,size_t len)
{
sc_apdu_t apdu;
u8 sbuff[SC_MAX_APDU_BUFFER_SIZE]={0};
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if(len>240)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_INCORRECT_PARAMETERS);
sbuff[0]=EC;
sbuff[1]=ver;
memcpy(&sbuff[2],data,len);
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF4,usage,key_id);
apdu.cla=0x84;
apdu.data=sbuff;
apdu.lc=apdu.datalen=len+2;
r=entersafe_transmit_apdu(card,&apdu,key_maintain,sizeof(key_maintain),1,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card, apdu.sw1, apdu.sw2),"Write prkey failed");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
static int entersafe_write_key(sc_card_t *card, sc_entersafe_wkey_data *data)
{
struct sc_pkcs15_prkey_rsa* rsa=data->key_data.rsa;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
switch(data->usage)
{
case 0x22:
if(rsa->modulus.len < 256)
return entersafe_write_small_rsa_key(card,data->key_id,rsa);
else
return entersafe_write_large_rsa_key(card,data->key_id,rsa);
break;
case 0x2A:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_NOT_SUPPORTED);
break;
default:
return entersafe_write_symmetric_key(card,data->key_id,data->usage,
data->key_data.symmetric.EC,
data->key_data.symmetric.ver,
data->key_data.symmetric.key_val,
data->key_data.symmetric.key_len);
break;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_gen_key(sc_card_t *card, sc_entersafe_gen_key_data *data)
{
int r;
size_t len = data->key_length >> 3;
sc_apdu_t apdu;
u8 rbuf[300];
u8 sbuf[4],*p;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* MSE */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x01, 0xB8);
apdu.lc=0x04;
sbuf[0]=0x83;
sbuf[1]=0x02;
sbuf[2]=data->key_id;
sbuf[3]=0x2A;
apdu.data = sbuf;
apdu.datalen=4;
apdu.lc=4;
apdu.le=0;
r=entersafe_transmit_apdu(card, &apdu, 0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe set MSE failed");
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.le = 0;
sbuf[0] = (u8)(data->key_length >> 8);
sbuf[1] = (u8)(data->key_length);
apdu.data = sbuf;
apdu.lc = 2;
apdu.datalen = 2;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe generate keypair failed");
/* read public key via READ PUBLIC KEY */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xE6, 0x2A, data->key_id);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get pukey failed");
data->modulus = malloc(len);
if (!data->modulus)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_OUT_OF_MEMORY);
p=rbuf;
assert(*p=='E');
p+=2+p[1];
/* N */
assert(*p=='N');
++p;
if(*p++>0x80)
{
u8 len_bytes=(*(p-1))&0x0f;
size_t module_len=0;
while(len_bytes!=0)
{
module_len=module_len<<8;
module_len+=*p++;
--len_bytes;
}
}
entersafe_reverse_buffer(p,len);
memcpy(data->modulus,p,len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
assert(serial);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT,0xEA,0x00,0x00);
apdu.cla=0x80;
apdu.resp=rbuf;
apdu.resplen=sizeof(rbuf);
apdu.le=0x08;
r=entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get SN failed");
card->serialnr.len=serial->len=8;
memcpy(card->serialnr.value,rbuf,8);
memcpy(serial->value,rbuf,8);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_preinstall_rsa_2048(sc_card_t *card,u8 key_id)
{
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
int ret=0;
static u8 const rsa_key_e[] =
{
'E', 0x04, 0x01, 0x00, 0x01, 0x00
};
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* create rsa item in IKF */
sbuf[0] = 0x04; /* key len extern */
sbuf[1] = 0x0a; /* key len */
sbuf[2] = 0x22; /* USAGE */
sbuf[3] = 0x34; /* user ac */
sbuf[4] = 0x04; /* change ac */
sbuf[5] = 0x34; /* UPDATE AC */
sbuf[6] = 0x40; /* ALGO */
sbuf[7] = 0x00; /* EC */
sbuf[8] = 0x00; /* VER */
memcpy(&sbuf[9], rsa_key_e, sizeof(rsa_key_e));
sbuf[9 + sizeof(rsa_key_e) + 0] = 'C'+'R'+'T';
sbuf[9 + sizeof(rsa_key_e) + 1] = 0x82;
sbuf[9 + sizeof(rsa_key_e) + 2] = 0x04;
sbuf[9 + sizeof(rsa_key_e) + 3] = 0x00;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT,0xF0,0x00,key_id);
apdu.cla=0x84;
apdu.data=sbuf;
apdu.lc=apdu.datalen=9 + sizeof(rsa_key_e) + 4;
ret = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, ret, "Preinstall rsa failed");
/* create rsa item in PKF */
sbuf[0] = 0x01; /* key len extern */
sbuf[1] = 0x0A; /* key len */
sbuf[2] = 0x2A; /* USAGE */
sbuf[3] = ENTERSAFE_AC_ALWAYS; /* user ac */
sbuf[4] = 0x04; /* change ac */
sbuf[5] = ENTERSAFE_AC_ALWAYS; /* UPDATE AC */
sbuf[6] = 0x40; /* ALGO */
sbuf[7] = 0x00; /* EC */
sbuf[8] = 0x00; /* VER */
memcpy(&sbuf[9], rsa_key_e, sizeof(rsa_key_e));
sbuf[9 + sizeof(rsa_key_e) + 0] = 'N';
sbuf[9 + sizeof(rsa_key_e) + 1] = 0x82;
sbuf[9 + sizeof(rsa_key_e) + 2] = 0x01;
sbuf[9 + sizeof(rsa_key_e) + 3] = 0x00;
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,key_id);
apdu.cla=0x84;
apdu.data=sbuf;
apdu.lc=apdu.datalen=9 + sizeof(rsa_key_e) + 4;
ret=entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, ret, "Preinstall rsa failed");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_preinstall_keys(sc_card_t *card,int (*install_rsa)(sc_card_t *,u8))
{
int r;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
{/* RSA */
u8 rsa_index;
for(rsa_index=ENTERSAFE_MIN_KEY_ID;
rsa_index<=ENTERSAFE_MAX_KEY_ID;
++rsa_index)
{
r=install_rsa(card,rsa_index);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall rsa key failed");
}
}
{/* key maintain */
/* create key maintain*/
sbuf[0] = 0; /* key len extern */
sbuf[1] = sizeof(key_maintain); /* key len */
sbuf[2] = 0x03; /* USAGE */
sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */
sbuf[4] = ENTERSAFE_AC_ALWAYS; /* CHANGE AC */
sbuf[5] = ENTERSAFE_AC_NEVER; /* UPDATE AC */
sbuf[6] = 0x01; /* ALGO */
sbuf[7] = 0x00; /* EC */
sbuf[8] = 0x00; /* VER */
memcpy(&sbuf[9], key_maintain, sizeof(key_maintain));
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,0x00);
apdu.cla=0x84;
apdu.data=sbuf;
apdu.lc=apdu.datalen=0x19;
r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall key maintain failed");
}
{/* user PIN */
memset(sbuf,0,sizeof(sbuf));
sbuf[0] = 0; /* key len extern */
sbuf[1] = 16; /* key len */
sbuf[2] = 0x0B; /* USAGE */
sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */
sbuf[4] = 0X04; /* CHANGE AC */
sbuf[5] = 0x38; /* UPDATE AC */
sbuf[6] = 0x01; /* ALGO */
sbuf[7] = 0xFF; /* EC */
sbuf[8] = 0x00; /* VER */
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,ENTERSAFE_USER_PIN_ID);
apdu.cla=0x84;
apdu.data=sbuf;
apdu.lc=apdu.datalen=0x19;
r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall user PIN failed");
}
{/* user PUK */
memset(sbuf,0,sizeof(sbuf));
sbuf[0] = 0; /* key len extern */
sbuf[1] = 16; /* key len */
sbuf[2] = 0x0B; /* USAGE */
sbuf[3] = ENTERSAFE_AC_ALWAYS; /* use AC */
sbuf[4] = 0X08; /* CHANGE AC */
sbuf[5] = 0xC0; /* UPDATE AC */
sbuf[6] = 0x01; /* ALGO */
sbuf[7] = 0xFF; /* EC */
sbuf[8] = 0x00; /* VER */
sc_format_apdu(card,&apdu,SC_APDU_CASE_3_SHORT,0xF0,0x00,ENTERSAFE_USER_PIN_ID+1);
apdu.cla=0x84;
apdu.data=sbuf;
apdu.lc=apdu.datalen=0x19;
r = entersafe_transmit_apdu(card,&apdu,init_key,sizeof(init_key),0,1);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Preinstall user PUK failed");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
static int entersafe_card_ctl_2048(sc_card_t *card, unsigned long cmd, void *ptr)
{
sc_entersafe_create_data *tmp = (sc_entersafe_create_data *)ptr;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
switch (cmd)
{
case SC_CARDCTL_ENTERSAFE_CREATE_FILE:
if (tmp->type == SC_ENTERSAFE_MF_DATA)
return entersafe_create_mf(card, tmp);
else if (tmp->type == SC_ENTERSAFE_DF_DATA)
return entersafe_create_df(card, tmp);
else if (tmp->type == SC_ENTERSAFE_EF_DATA)
return entersafe_create_ef(card, tmp);
else
return SC_ERROR_INTERNAL;
case SC_CARDCTL_ENTERSAFE_WRITE_KEY:
return entersafe_write_key(card, (sc_entersafe_wkey_data *)ptr);
case SC_CARDCTL_ENTERSAFE_GENERATE_KEY:
return entersafe_gen_key(card, (sc_entersafe_gen_key_data *)ptr);
case SC_CARDCTL_ERASE_CARD:
return entersafe_erase_card(card);
case SC_CARDCTL_GET_SERIALNR:
return entersafe_get_serialnr(card, (sc_serial_number_t *)ptr);
case SC_CARDCTL_ENTERSAFE_PREINSTALL_KEYS:
return entersafe_preinstall_keys(card,entersafe_preinstall_rsa_2048);
default:
return SC_ERROR_NOT_SUPPORTED;
}
}
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;
entersafe_ops = *iso_drv->ops;
entersafe_ops.match_card = entersafe_match_card;
entersafe_ops.init = entersafe_init;
entersafe_ops.read_binary = entersafe_read_binary;
entersafe_ops.write_binary = NULL;
entersafe_ops.update_binary = entersafe_update_binary;
entersafe_ops.select_file = entersafe_select_file;
entersafe_ops.restore_security_env = entersafe_restore_security_env;
entersafe_ops.set_security_env = entersafe_set_security_env;
entersafe_ops.decipher = entersafe_decipher;
entersafe_ops.compute_signature = entersafe_compute_signature;
entersafe_ops.create_file = entersafe_create_file;
entersafe_ops.delete_file = NULL;
entersafe_ops.pin_cmd = entersafe_pin_cmd;
entersafe_ops.card_ctl = entersafe_card_ctl_2048;
entersafe_ops.process_fci = entersafe_process_fci;
return &entersafe_drv;
}
struct sc_card_driver * sc_get_entersafe_driver(void)
{
return sc_get_driver();
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_5 |
crossvul-cpp_data_bad_4540_0 | /* pb_decode.c -- decode a protobuf using minimal resources
*
* 2011 Petteri Aimonen <jpa@kapsi.fi>
*/
/* Use the GCC warn_unused_result attribute to check that all return values
* are propagated correctly. On other compilers and gcc before 3.4.0 just
* ignore the annotation.
*/
#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
#define checkreturn
#else
#define checkreturn __attribute__((warn_unused_result))
#endif
#include "pb.h"
#include "pb_decode.h"
/**************************************
* Declarations internal to this file *
**************************************/
/* Iterator for pb_field_t list */
typedef struct {
const pb_field_t *start; /* Start of the pb_field_t array */
const pb_field_t *pos; /* Current position of the iterator */
unsigned field_index; /* Zero-based index of the field. */
unsigned required_field_index; /* Zero-based index that counts only the required fields */
void *dest_struct; /* Pointer to the destination structure to decode to */
void *pData; /* Pointer where to store current field value */
void *pSize; /* Pointer where to store the size of current array field */
} pb_field_iterator_t;
typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;
static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count);
static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest);
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size);
static void pb_field_init(pb_field_iterator_t *iter, const pb_field_t *fields, void *dest_struct);
static bool pb_field_next(pb_field_iterator_t *iter);
static bool checkreturn pb_field_find(pb_field_iterator_t *iter, uint32_t tag);
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
static void iter_from_extension(pb_field_iterator_t *iter, pb_extension_t *extension);
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
static bool checkreturn find_extension_field(pb_field_iterator_t *iter);
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
static bool checkreturn pb_skip_string(pb_istream_t *stream);
#ifdef PB_ENABLE_MALLOC
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);
static void pb_release_single_field(const pb_field_iterator_t *iter);
#endif
/* --- Function pointers to field decoders ---
* Order in the array must match pb_action_t LTYPE numbering.
*/
static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
&pb_dec_varint,
&pb_dec_uvarint,
&pb_dec_svarint,
&pb_dec_fixed32,
&pb_dec_fixed64,
&pb_dec_bytes,
&pb_dec_string,
&pb_dec_submessage,
NULL /* extensions */
};
/*******************************
* pb_istream_t implementation *
*******************************/
static bool checkreturn buf_read(pb_istream_t *stream, uint8_t *buf, size_t count)
{
uint8_t *source = (uint8_t*)stream->state;
stream->state = source + count;
if (buf != NULL)
{
while (count--)
*buf++ = *source++;
}
return true;
}
bool checkreturn pb_read(pb_istream_t *stream, uint8_t *buf, size_t count)
{
#ifndef PB_BUFFER_ONLY
if (buf == NULL && stream->callback != buf_read)
{
/* Skip input bytes */
uint8_t tmp[16];
while (count > 16)
{
if (!pb_read(stream, tmp, 16))
return false;
count -= 16;
}
return pb_read(stream, tmp, count);
}
#endif
if (stream->bytes_left < count)
PB_RETURN_ERROR(stream, "end-of-stream");
#ifndef PB_BUFFER_ONLY
if (!stream->callback(stream, buf, count))
PB_RETURN_ERROR(stream, "io error");
#else
if (!buf_read(stream, buf, count))
return false;
#endif
stream->bytes_left -= count;
return true;
}
/* Read a single byte from input stream. buf may not be NULL.
* This is an optimization for the varint decoding. */
static bool checkreturn pb_readbyte(pb_istream_t *stream, uint8_t *buf)
{
if (stream->bytes_left == 0)
PB_RETURN_ERROR(stream, "end-of-stream");
#ifndef PB_BUFFER_ONLY
if (!stream->callback(stream, buf, 1))
PB_RETURN_ERROR(stream, "io error");
#else
*buf = *(uint8_t*)stream->state;
stream->state = (uint8_t*)stream->state + 1;
#endif
stream->bytes_left--;
return true;
}
pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize)
{
pb_istream_t stream;
#ifdef PB_BUFFER_ONLY
stream.callback = NULL;
#else
stream.callback = &buf_read;
#endif
stream.state = buf;
stream.bytes_left = bufsize;
#ifndef PB_NO_ERRMSG
stream.errmsg = NULL;
#endif
return stream;
}
/********************
* Helper functions *
********************/
static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
{
uint8_t byte;
uint32_t result;
if (!pb_readbyte(stream, &byte))
return false;
if ((byte & 0x80) == 0)
{
/* Quick case, 1 byte value */
result = byte;
}
else
{
/* Multibyte case */
uint8_t bitpos = 7;
result = byte & 0x7F;
do
{
if (bitpos >= 32)
PB_RETURN_ERROR(stream, "varint overflow");
if (!pb_readbyte(stream, &byte))
return false;
result |= (uint32_t)(byte & 0x7F) << bitpos;
bitpos = (uint8_t)(bitpos + 7);
} while (byte & 0x80);
}
*dest = result;
return true;
}
bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
{
uint8_t byte;
uint8_t bitpos = 0;
uint64_t result = 0;
do
{
if (bitpos >= 64)
PB_RETURN_ERROR(stream, "varint overflow");
if (!pb_readbyte(stream, &byte))
return false;
result |= (uint64_t)(byte & 0x7F) << bitpos;
bitpos = (uint8_t)(bitpos + 7);
} while (byte & 0x80);
*dest = result;
return true;
}
bool checkreturn pb_skip_varint(pb_istream_t *stream)
{
uint8_t byte;
do
{
if (!pb_read(stream, &byte, 1))
return false;
} while (byte & 0x80);
return true;
}
bool checkreturn pb_skip_string(pb_istream_t *stream)
{
uint32_t length;
if (!pb_decode_varint32(stream, &length))
return false;
return pb_read(stream, NULL, length);
}
bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
{
uint32_t temp;
*eof = false;
*wire_type = (pb_wire_type_t) 0;
*tag = 0;
if (!pb_decode_varint32(stream, &temp))
{
if (stream->bytes_left == 0)
*eof = true;
return false;
}
if (temp == 0)
{
*eof = true; /* Special feature: allow 0-terminated messages. */
return false;
}
*tag = temp >> 3;
*wire_type = (pb_wire_type_t)(temp & 7);
return true;
}
bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
{
switch (wire_type)
{
case PB_WT_VARINT: return pb_skip_varint(stream);
case PB_WT_64BIT: return pb_read(stream, NULL, 8);
case PB_WT_STRING: return pb_skip_string(stream);
case PB_WT_32BIT: return pb_read(stream, NULL, 4);
default: PB_RETURN_ERROR(stream, "invalid wire_type");
}
}
/* Read a raw value to buffer, for the purpose of passing it to callback as
* a substream. Size is maximum size on call, and actual size on return.
*/
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, uint8_t *buf, size_t *size)
{
size_t max_size = *size;
switch (wire_type)
{
case PB_WT_VARINT:
*size = 0;
do
{
(*size)++;
if (*size > max_size) return false;
if (!pb_read(stream, buf, 1)) return false;
} while (*buf++ & 0x80);
return true;
case PB_WT_64BIT:
*size = 8;
return pb_read(stream, buf, 8);
case PB_WT_32BIT:
*size = 4;
return pb_read(stream, buf, 4);
default: PB_RETURN_ERROR(stream, "invalid wire_type");
}
}
/* Decode string length from stream and return a substream with limited length.
* Remember to close the substream using pb_close_string_substream().
*/
bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
uint32_t size;
if (!pb_decode_varint32(stream, &size))
return false;
*substream = *stream;
if (substream->bytes_left < size)
PB_RETURN_ERROR(stream, "parent stream too short");
substream->bytes_left = size;
stream->bytes_left -= size;
return true;
}
void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
stream->state = substream->state;
#ifndef PB_NO_ERRMSG
stream->errmsg = substream->errmsg;
#endif
}
static void pb_field_init(pb_field_iterator_t *iter, const pb_field_t *fields, void *dest_struct)
{
iter->start = iter->pos = fields;
iter->field_index = 0;
iter->required_field_index = 0;
iter->pData = (char*)dest_struct + iter->pos->data_offset;
iter->pSize = (char*)iter->pData + iter->pos->size_offset;
iter->dest_struct = dest_struct;
}
static bool pb_field_next(pb_field_iterator_t *iter)
{
bool notwrapped = true;
size_t prev_size = iter->pos->data_size;
if (PB_ATYPE(iter->pos->type) == PB_ATYPE_STATIC &&
PB_HTYPE(iter->pos->type) == PB_HTYPE_REPEATED)
{
prev_size *= iter->pos->array_size;
}
else if (PB_ATYPE(iter->pos->type) == PB_ATYPE_POINTER)
{
prev_size = sizeof(void*);
}
if (iter->pos->tag == 0)
return false; /* Only happens with empty message types */
if (PB_HTYPE(iter->pos->type) == PB_HTYPE_REQUIRED)
iter->required_field_index++;
iter->pos++;
iter->field_index++;
if (iter->pos->tag == 0)
{
iter->pos = iter->start;
iter->field_index = 0;
iter->required_field_index = 0;
iter->pData = iter->dest_struct;
prev_size = 0;
notwrapped = false;
}
iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset;
iter->pSize = (char*)iter->pData + iter->pos->size_offset;
return notwrapped;
}
static bool checkreturn pb_field_find(pb_field_iterator_t *iter, uint32_t tag)
{
unsigned start = iter->field_index;
do {
if (iter->pos->tag == tag &&
PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION)
{
return true;
}
(void)pb_field_next(iter);
} while (iter->field_index != start);
return false;
}
/*************************
* Decode a single field *
*************************/
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
{
pb_type_t type;
pb_decoder_t func;
type = iter->pos->type;
func = PB_DECODERS[PB_LTYPE(type)];
switch (PB_HTYPE(type))
{
case PB_HTYPE_REQUIRED:
return func(stream, iter->pos, iter->pData);
case PB_HTYPE_OPTIONAL:
*(bool*)iter->pSize = true;
return func(stream, iter->pos, iter->pData);
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array */
bool status = true;
size_t *size = (size_t*)iter->pSize;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left > 0 && *size < iter->pos->array_size)
{
void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
if (!func(&substream, iter->pos, pItem))
{
status = false;
break;
}
(*size)++;
}
pb_close_string_substream(stream, &substream);
if (substream.bytes_left != 0)
PB_RETURN_ERROR(stream, "array overflow");
return status;
}
else
{
/* Repeated field */
size_t *size = (size_t*)iter->pSize;
void *pItem = (uint8_t*)iter->pData + iter->pos->data_size * (*size);
if (*size >= iter->pos->array_size)
PB_RETURN_ERROR(stream, "array overflow");
(*size)++;
return func(stream, iter->pos, pItem);
}
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
#ifdef PB_ENABLE_MALLOC
/* Allocate storage for the field and store the pointer at iter->pData.
* array_size is the number of entries to reserve in an array.
* Zero size is not allowed, use pb_free() for releasing.
*/
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
{
void *ptr = *(void**)pData;
if (data_size == 0 || array_size == 0)
PB_RETURN_ERROR(stream, "invalid size");
#ifdef __AVR__
/* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284
* Realloc to size of 1 byte can cause corruption of the malloc structures.
*/
if (data_size == 1 && array_size == 1)
{
data_size = 2;
}
#endif
/* Check for multiplication overflows.
* This code avoids the costly division if the sizes are small enough.
* Multiplication is safe as long as only half of bits are set
* in either multiplicand.
*/
{
const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
if (data_size >= check_limit || array_size >= check_limit)
{
const size_t size_max = (size_t)-1;
if (size_max / array_size < data_size)
{
PB_RETURN_ERROR(stream, "size too large");
}
}
}
/* Allocate new or expand previous allocation */
/* Note: on failure the old pointer will remain in the structure,
* the message must be freed by caller also on error return. */
ptr = pb_realloc(ptr, array_size * data_size);
if (ptr == NULL)
PB_RETURN_ERROR(stream, "realloc failed");
*(void**)pData = ptr;
return true;
}
/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
static void initialize_pointer_field(void *pItem, pb_field_iterator_t *iter)
{
if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||
PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)
{
*(void**)pItem = NULL;
}
else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
{
pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);
}
}
#endif
static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
{
#ifndef PB_ENABLE_MALLOC
UNUSED(wire_type);
UNUSED(iter);
PB_RETURN_ERROR(stream, "no malloc support");
#else
pb_type_t type;
pb_decoder_t func;
type = iter->pos->type;
func = PB_DECODERS[PB_LTYPE(type)];
switch (PB_HTYPE(type))
{
case PB_HTYPE_REQUIRED:
case PB_HTYPE_OPTIONAL:
if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
*(void**)iter->pData != NULL)
{
/* Duplicate field, have to release the old allocation first. */
pb_release_single_field(iter);
}
if (PB_LTYPE(type) == PB_LTYPE_STRING ||
PB_LTYPE(type) == PB_LTYPE_BYTES)
{
return func(stream, iter->pos, iter->pData);
}
else
{
if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))
return false;
initialize_pointer_field(*(void**)iter->pData, iter);
return func(stream, iter->pos, *(void**)iter->pData);
}
case PB_HTYPE_REPEATED:
if (wire_type == PB_WT_STRING
&& PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
{
/* Packed array, multiple items come in at once. */
bool status = true;
size_t *size = (size_t*)iter->pSize;
size_t allocated_size = *size;
void *pItem;
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
while (substream.bytes_left)
{
if (*size + 1 > allocated_size)
{
/* Allocate more storage. This tries to guess the
* number of remaining entries. Round the division
* upwards. */
allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;
if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))
{
status = false;
break;
}
}
/* Decode the array entry */
pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size);
initialize_pointer_field(pItem, iter);
if (!func(&substream, iter->pos, pItem))
{
status = false;
break;
}
(*size)++;
}
pb_close_string_substream(stream, &substream);
return status;
}
else
{
/* Normal repeated field, i.e. only one item at a time. */
size_t *size = (size_t*)iter->pSize;
void *pItem;
(*size)++;
if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))
return false;
pItem = *(uint8_t**)iter->pData + iter->pos->data_size * (*size - 1);
initialize_pointer_field(pItem, iter);
return func(stream, iter->pos, pItem);
}
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
#endif
}
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
{
pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
#ifdef PB_OLD_CALLBACK_STYLE
void *arg = pCallback->arg;
#else
void **arg = &(pCallback->arg);
#endif
if (pCallback->funcs.decode == NULL)
return pb_skip_field(stream, wire_type);
if (wire_type == PB_WT_STRING)
{
pb_istream_t substream;
if (!pb_make_string_substream(stream, &substream))
return false;
do
{
if (!pCallback->funcs.decode(&substream, iter->pos, arg))
PB_RETURN_ERROR(stream, "callback failed");
} while (substream.bytes_left);
pb_close_string_substream(stream, &substream);
return true;
}
else
{
/* Copy the single scalar value to stack.
* This is required so that we can limit the stream length,
* which in turn allows to use same callback for packed and
* not-packed fields. */
pb_istream_t substream;
uint8_t buffer[10];
size_t size = sizeof(buffer);
if (!read_raw_value(stream, wire_type, buffer, &size))
return false;
substream = pb_istream_from_buffer(buffer, size);
return pCallback->funcs.decode(&substream, iter->pos, arg);
}
}
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
{
switch (PB_ATYPE(iter->pos->type))
{
case PB_ATYPE_STATIC:
return decode_static_field(stream, wire_type, iter);
case PB_ATYPE_POINTER:
return decode_pointer_field(stream, wire_type, iter);
case PB_ATYPE_CALLBACK:
return decode_callback_field(stream, wire_type, iter);
default:
PB_RETURN_ERROR(stream, "invalid field type");
}
}
static void iter_from_extension(pb_field_iterator_t *iter, pb_extension_t *extension)
{
const pb_field_t *field = (const pb_field_t*)extension->type->arg;
iter->start = field;
iter->pos = field;
iter->field_index = 0;
iter->required_field_index = 0;
iter->dest_struct = extension->dest;
iter->pData = extension->dest;
iter->pSize = &extension->found;
}
/* Default handler for extension fields. Expects a pb_field_t structure
* in extension->type->arg. */
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
{
const pb_field_t *field = (const pb_field_t*)extension->type->arg;
pb_field_iterator_t iter;
if (field->tag != tag)
return true;
iter_from_extension(&iter, extension);
return decode_field(stream, wire_type, &iter);
}
/* Try to decode an unknown field as an extension field. Tries each extension
* decoder in turn, until one of them handles the field or loop ends. */
static bool checkreturn decode_extension(pb_istream_t *stream,
uint32_t tag, pb_wire_type_t wire_type, pb_field_iterator_t *iter)
{
pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
size_t pos = stream->bytes_left;
while (extension != NULL && pos == stream->bytes_left)
{
bool status;
if (extension->type->decode)
status = extension->type->decode(stream, extension, tag, wire_type);
else
status = default_extension_decoder(stream, extension, tag, wire_type);
if (!status)
return false;
extension = extension->next;
}
return true;
}
/* Step through the iterator until an extension field is found or until all
* entries have been checked. There can be only one extension field per
* message. Returns false if no extension field is found. */
static bool checkreturn find_extension_field(pb_field_iterator_t *iter)
{
unsigned start = iter->field_index;
do {
if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
return true;
(void)pb_field_next(iter);
} while (iter->field_index != start);
return false;
}
/* Initialize message fields to default values, recursively */
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
{
pb_field_iterator_t iter;
pb_field_init(&iter, fields, dest_struct);
do
{
pb_type_t type;
type = iter.pos->type;
/* Avoid crash on empty message types (zero fields) */
if (iter.pos->tag == 0)
continue;
if (PB_ATYPE(type) == PB_ATYPE_STATIC)
{
if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
{
/* Set has_field to false. Still initialize the optional field
* itself also. */
*(bool*)iter.pSize = false;
}
else if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
/* Set array count to 0, no need to initialize contents. */
*(size_t*)iter.pSize = 0;
continue;
}
if (PB_LTYPE(iter.pos->type) == PB_LTYPE_SUBMESSAGE)
{
/* Initialize submessage to defaults */
pb_message_set_to_defaults((const pb_field_t *) iter.pos->ptr, iter.pData);
}
else if (iter.pos->ptr != NULL)
{
/* Initialize to default value */
memcpy(iter.pData, iter.pos->ptr, iter.pos->data_size);
}
else
{
/* Initialize to zeros */
memset(iter.pData, 0, iter.pos->data_size);
}
}
else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
/* Initialize the pointer to NULL. */
*(void**)iter.pData = NULL;
/* Initialize array count to 0. */
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
*(size_t*)iter.pSize = 0;
}
}
else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
{
/* Don't overwrite callback */
}
} while (pb_field_next(&iter));
}
/*********************
* Decode all fields *
*********************/
bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
uint8_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 7) / 8] = {0, 0, 0, 0, 0, 0, 0, 0};
uint32_t extension_range_start = 0;
pb_field_iterator_t iter;
pb_field_init(&iter, fields, dest_struct);
while (stream->bytes_left)
{
uint32_t tag;
pb_wire_type_t wire_type;
bool eof;
if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
{
if (eof)
break;
else
return false;
}
if (!pb_field_find(&iter, tag))
{
/* No match found, check if it matches an extension. */
if (tag >= extension_range_start)
{
if (!find_extension_field(&iter))
extension_range_start = (uint32_t)-1;
else
extension_range_start = iter.pos->tag;
if (tag >= extension_range_start)
{
size_t pos = stream->bytes_left;
if (!decode_extension(stream, tag, wire_type, &iter))
return false;
if (pos != stream->bytes_left)
{
/* The field was handled */
continue;
}
}
}
/* No match found, skip data */
if (!pb_skip_field(stream, wire_type))
return false;
continue;
}
if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
&& iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
{
fields_seen[iter.required_field_index >> 3] |= (uint8_t)(1 << (iter.required_field_index & 7));
}
if (!decode_field(stream, wire_type, &iter))
return false;
}
/* Check that all required fields were present. */
{
/* First figure out the number of required fields by
* seeking to the end of the field array. Usually we
* are already close to end after decoding.
*/
unsigned req_field_count;
pb_type_t last_type;
unsigned i;
do {
req_field_count = iter.required_field_index;
last_type = iter.pos->type;
} while (pb_field_next(&iter));
/* Fixup if last field was also required. */
if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
req_field_count++;
/* Check the whole bytes */
for (i = 0; i < (req_field_count >> 3); i++)
{
if (fields_seen[i] != 0xFF)
PB_RETURN_ERROR(stream, "missing required field");
}
/* Check the remaining bits */
if (fields_seen[req_field_count >> 3] != (0xFF >> (8 - (req_field_count & 7))))
PB_RETURN_ERROR(stream, "missing required field");
}
return true;
}
bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
bool status;
pb_message_set_to_defaults(fields, dest_struct);
status = pb_decode_noinit(stream, fields, dest_struct);
#ifdef PB_ENABLE_MALLOC
if (!status)
pb_release(fields, dest_struct);
#endif
return status;
}
bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
pb_istream_t substream;
bool status;
if (!pb_make_string_substream(stream, &substream))
return false;
status = pb_decode(&substream, fields, dest_struct);
pb_close_string_substream(stream, &substream);
return status;
}
#ifdef PB_ENABLE_MALLOC
static void pb_release_single_field(const pb_field_iterator_t *iter)
{
pb_type_t type;
type = iter->pos->type;
/* Release anything contained inside an extension or submsg.
* This has to be done even if the submsg itself is statically
* allocated. */
if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
{
/* Release fields from all extensions in the linked list */
pb_extension_t *ext = *(pb_extension_t**)iter->pData;
while (ext != NULL)
{
pb_field_iterator_t ext_iter;
iter_from_extension(&ext_iter, ext);
pb_release_single_field(&ext_iter);
ext = ext->next;
}
}
else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
{
/* Release fields in submessage or submsg array */
void *pItem = iter->pData;
pb_size_t count = 1;
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
pItem = *(void**)iter->pData;
}
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
count = *(pb_size_t*)iter->pSize;
if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)
{
/* Protect against corrupted _count fields */
count = iter->pos->array_size;
}
}
if (pItem)
{
while (count--)
{
pb_release((const pb_field_t*)iter->pos->ptr, pItem);
pItem = (uint8_t*)pItem + iter->pos->data_size;
}
}
}
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
{
if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
(PB_LTYPE(type) == PB_LTYPE_STRING ||
PB_LTYPE(type) == PB_LTYPE_BYTES))
{
/* Release entries in repeated string or bytes array */
void **pItem = *(void***)iter->pData;
pb_size_t count = *(pb_size_t*)iter->pSize;
while (count--)
{
pb_free(*pItem);
*pItem++ = NULL;
}
}
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
{
/* We are going to release the array, so set the size to 0 */
*(pb_size_t*)iter->pSize = 0;
}
/* Release main item */
pb_free(*(void**)iter->pData);
*(void**)iter->pData = NULL;
}
}
void pb_release(const pb_field_t fields[], void *dest_struct)
{
pb_field_iterator_t iter;
pb_field_init(&iter, fields, dest_struct);
if (iter.pos->tag == 0)
return; /* Empty message type */
do
{
pb_release_single_field(&iter);
} while (pb_field_next(&iter));
}
#endif
/* Field decoders */
bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
{
uint64_t value;
if (!pb_decode_varint(stream, &value))
return false;
if (value & 1)
*dest = (int64_t)(~(value >> 1));
else
*dest = (int64_t)(value >> 1);
return true;
}
bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
{
#ifdef __BIG_ENDIAN__
uint8_t *bytes = (uint8_t*)dest;
uint8_t lebytes[4];
if (!pb_read(stream, lebytes, 4))
return false;
bytes[0] = lebytes[3];
bytes[1] = lebytes[2];
bytes[2] = lebytes[1];
bytes[3] = lebytes[0];
return true;
#else
return pb_read(stream, (uint8_t*)dest, 4);
#endif
}
bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
{
#ifdef __BIG_ENDIAN__
uint8_t *bytes = (uint8_t*)dest;
uint8_t lebytes[8];
if (!pb_read(stream, lebytes, 8))
return false;
bytes[0] = lebytes[7];
bytes[1] = lebytes[6];
bytes[2] = lebytes[5];
bytes[3] = lebytes[4];
bytes[4] = lebytes[3];
bytes[5] = lebytes[2];
bytes[6] = lebytes[1];
bytes[7] = lebytes[0];
return true;
#else
return pb_read(stream, (uint8_t*)dest, 8);
#endif
}
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint64_t value;
if (!pb_decode_varint(stream, &value))
return false;
switch (field->data_size)
{
case 1: *(int8_t*)dest = (int8_t)value; break;
case 2: *(int16_t*)dest = (int16_t)value; break;
case 4: *(int32_t*)dest = (int32_t)value; break;
case 8: *(int64_t*)dest = (int64_t)value; break;
default: PB_RETURN_ERROR(stream, "invalid data_size");
}
return true;
}
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint64_t value;
if (!pb_decode_varint(stream, &value))
return false;
switch (field->data_size)
{
case 4: *(uint32_t*)dest = (uint32_t)value; break;
case 8: *(uint64_t*)dest = value; break;
default: PB_RETURN_ERROR(stream, "invalid data_size");
}
return true;
}
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
int64_t value;
if (!pb_decode_svarint(stream, &value))
return false;
switch (field->data_size)
{
case 4: *(int32_t*)dest = (int32_t)value; break;
case 8: *(int64_t*)dest = value; break;
default: PB_RETURN_ERROR(stream, "invalid data_size");
}
return true;
}
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
UNUSED(field);
return pb_decode_fixed32(stream, dest);
}
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
UNUSED(field);
return pb_decode_fixed64(stream, dest);
}
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint32_t size;
size_t alloc_size;
pb_bytes_array_t *bdest;
if (!pb_decode_varint32(stream, &size))
return false;
alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
if (size > alloc_size)
PB_RETURN_ERROR(stream, "size too large");
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
#ifndef PB_ENABLE_MALLOC
PB_RETURN_ERROR(stream, "no malloc support");
#else
if (!allocate_field(stream, dest, alloc_size, 1))
return false;
bdest = *(pb_bytes_array_t**)dest;
#endif
}
else
{
if (alloc_size > field->data_size)
PB_RETURN_ERROR(stream, "bytes overflow");
bdest = (pb_bytes_array_t*)dest;
}
bdest->size = size;
return pb_read(stream, bdest->bytes, size);
}
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
uint32_t size;
size_t alloc_size;
bool status;
if (!pb_decode_varint32(stream, &size))
return false;
/* Space for null terminator */
alloc_size = size + 1;
if (alloc_size < size)
PB_RETURN_ERROR(stream, "size too large");
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
{
#ifndef PB_ENABLE_MALLOC
PB_RETURN_ERROR(stream, "no malloc support");
#else
if (!allocate_field(stream, dest, alloc_size, 1))
return false;
dest = *(void**)dest;
#endif
}
else
{
if (alloc_size > field->data_size)
PB_RETURN_ERROR(stream, "string overflow");
}
status = pb_read(stream, (uint8_t*)dest, size);
*((uint8_t*)dest + size) = 0;
return status;
}
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
bool status;
pb_istream_t substream;
const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
if (!pb_make_string_substream(stream, &substream))
return false;
if (field->ptr == NULL)
PB_RETURN_ERROR(stream, "invalid field descriptor");
/* New array entries need to be initialized, while required and optional
* submessages have already been initialized in the top-level pb_decode. */
if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
status = pb_decode(&substream, submsg_fields, dest);
else
status = pb_decode_noinit(&substream, submsg_fields, dest);
pb_close_string_substream(stream, &substream);
return status;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4540_0 |
crossvul-cpp_data_good_2442_0 | /*
* base64.c
* base64 encode/decode implementation
*
* Copyright (c) 2011 Nikias Bassen, All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <string.h>
#include "base64.h"
static const char base64_str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char base64_pad = '=';
static const signed char base64_table[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
size_t base64encode(char *outbuf, const unsigned char *buf, size_t size)
{
if (!outbuf || !buf || (size <= 0)) {
return 0;
}
size_t n = 0;
size_t m = 0;
unsigned char input[3];
unsigned int output[4];
while (n < size) {
input[0] = buf[n];
input[1] = (n+1 < size) ? buf[n+1] : 0;
input[2] = (n+2 < size) ? buf[n+2] : 0;
output[0] = input[0] >> 2;
output[1] = ((input[0] & 3) << 4) + (input[1] >> 4);
output[2] = ((input[1] & 15) << 2) + (input[2] >> 6);
output[3] = input[2] & 63;
outbuf[m++] = base64_str[(int)output[0]];
outbuf[m++] = base64_str[(int)output[1]];
outbuf[m++] = (n+1 < size) ? base64_str[(int)output[2]] : base64_pad;
outbuf[m++] = (n+2 < size) ? base64_str[(int)output[3]] : base64_pad;
n+=3;
}
outbuf[m] = 0; // 0-termination!
return m;
}
unsigned char *base64decode(const char *buf, size_t *size)
{
if (!buf || !size) return NULL;
size_t len = (*size > 0) ? *size : strlen(buf);
if (len <= 0) return NULL;
unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3);
const char *ptr = buf;
int p = 0;
int wv, w1, w2, w3, w4;
int tmpval[4];
int tmpcnt = 0;
do {
while (ptr < buf+len && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n' || *ptr == '\r')) {
ptr++;
}
if (*ptr == '\0' || ptr >= buf+len) {
break;
}
if ((wv = base64_table[(int)(unsigned char)*ptr++]) == -1) {
continue;
}
tmpval[tmpcnt++] = wv;
if (tmpcnt == 4) {
tmpcnt = 0;
w1 = tmpval[0];
w2 = tmpval[1];
w3 = tmpval[2];
w4 = tmpval[3];
if (w2 >= 0) {
outbuf[p++] = (unsigned char)(((w1 << 2) + (w2 >> 4)) & 0xFF);
}
if (w3 >= 0) {
outbuf[p++] = (unsigned char)(((w2 << 4) + (w3 >> 2)) & 0xFF);
}
if (w4 >= 0) {
outbuf[p++] = (unsigned char)(((w3 << 6) + w4) & 0xFF);
}
}
} while (1);
outbuf[p] = 0;
*size = p;
return outbuf;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2442_0 |
crossvul-cpp_data_good_4838_0 | /* Copyright 2006-2007 Niels Provos
* Copyright 2007-2012 Nick Mathewson and Niels Provos
*
* 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 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 software by Adam Langly. Adam's original message:
*
* Async DNS Library
* Adam Langley <agl@imperialviolet.org>
* http://www.imperialviolet.org/eventdns.html
* Public Domain code
*
* This software is Public Domain. To view a copy of the public domain dedication,
* visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
* Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
*
* I ask and expect, but do not require, that all derivative works contain an
* attribution similar to:
* Parts developed by Adam Langley <agl@imperialviolet.org>
*
* You may wish to replace the word "Parts" with something else depending on
* the amount of original code.
*
* (Derivative works does not include programs which link against, run or include
* the source verbatim in their source distributions)
*
* Version: 0.1b
*/
#include "event2/event-config.h"
#include "evconfig-private.h"
#include <sys/types.h>
#ifndef _FORTIFY_SOURCE
#define _FORTIFY_SOURCE 3
#endif
#include <string.h>
#include <fcntl.h>
#ifdef EVENT__HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef EVENT__HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifdef EVENT__HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <limits.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdarg.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#ifndef _WIN32_IE
#define _WIN32_IE 0x400
#endif
#include <shlobj.h>
#endif
#include "event2/dns.h"
#include "event2/dns_struct.h"
#include "event2/dns_compat.h"
#include "event2/util.h"
#include "event2/event.h"
#include "event2/event_struct.h"
#include "event2/thread.h"
#include "defer-internal.h"
#include "log-internal.h"
#include "mm-internal.h"
#include "strlcpy-internal.h"
#include "ipv6-internal.h"
#include "util-internal.h"
#include "evthread-internal.h"
#ifdef _WIN32
#include <ctype.h>
#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
#include <io.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef EVENT__HAVE_NETINET_IN6_H
#include <netinet/in6.h>
#endif
#define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
#define EVDNS_LOG_WARN EVENT_LOG_WARN
#define EVDNS_LOG_MSG EVENT_LOG_MSG
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif
#include <stdio.h>
#undef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#define ASSERT_VALID_REQUEST(req) \
EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
#define u64 ev_uint64_t
#define u32 ev_uint32_t
#define u16 ev_uint16_t
#define u8 ev_uint8_t
/* maximum number of addresses from a single packet */
/* that we bother recording */
#define MAX_V4_ADDRS 32
#define MAX_V6_ADDRS 32
#define TYPE_A EVDNS_TYPE_A
#define TYPE_CNAME 5
#define TYPE_PTR EVDNS_TYPE_PTR
#define TYPE_SOA EVDNS_TYPE_SOA
#define TYPE_AAAA EVDNS_TYPE_AAAA
#define CLASS_INET EVDNS_CLASS_INET
/* Persistent handle. We keep this separate from 'struct request' since we
* need some object to last for as long as an evdns_request is outstanding so
* that it can be canceled, whereas a search request can lead to multiple
* 'struct request' instances being created over its lifetime. */
struct evdns_request {
struct request *current_req;
struct evdns_base *base;
int pending_cb; /* Waiting for its callback to be invoked; not
* owned by event base any more. */
/* elements used by the searching code */
int search_index;
struct search_state *search_state;
char *search_origname; /* needs to be free()ed */
int search_flags;
};
struct request {
u8 *request; /* the dns packet data */
u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
unsigned int request_len;
int reissue_count;
int tx_count; /* the number of times that this packet has been sent */
void *user_pointer; /* the pointer given to us for this request */
evdns_callback_type user_callback;
struct nameserver *ns; /* the server which we last sent it */
/* these objects are kept in a circular list */
/* XXX We could turn this into a CIRCLEQ. */
struct request *next, *prev;
struct event timeout_event;
u16 trans_id; /* the transaction id */
unsigned request_appended :1; /* true if the request pointer is data which follows this struct */
unsigned transmit_me :1; /* needs to be transmitted */
/* XXXX This is a horrible hack. */
char **put_cname_in_ptr; /* store the cname here if we get one. */
struct evdns_base *base;
struct evdns_request *handle;
};
struct reply {
unsigned int type;
unsigned int have_answer : 1;
union {
struct {
u32 addrcount;
u32 addresses[MAX_V4_ADDRS];
} a;
struct {
u32 addrcount;
struct in6_addr addresses[MAX_V6_ADDRS];
} aaaa;
struct {
char name[HOST_NAME_MAX];
} ptr;
} data;
};
struct nameserver {
evutil_socket_t socket; /* a connected UDP socket */
struct sockaddr_storage address;
ev_socklen_t addrlen;
int failed_times; /* number of times which we have given this server a chance */
int timedout; /* number of times in a row a request has timed out */
struct event event;
/* these objects are kept in a circular list */
struct nameserver *next, *prev;
struct event timeout_event; /* used to keep the timeout for */
/* when we next probe this server. */
/* Valid if state == 0 */
/* Outstanding probe request for this nameserver, if any */
struct evdns_request *probe_request;
char state; /* zero if we think that this server is down */
char choked; /* true if we have an EAGAIN from this server's socket */
char write_waiting; /* true if we are waiting for EV_WRITE events */
struct evdns_base *base;
/* Number of currently inflight requests: used
* to track when we should add/del the event. */
int requests_inflight;
};
/* Represents a local port where we're listening for DNS requests. Right now, */
/* only UDP is supported. */
struct evdns_server_port {
evutil_socket_t socket; /* socket we use to read queries and write replies. */
int refcnt; /* reference count. */
char choked; /* Are we currently blocked from writing? */
char closing; /* Are we trying to close this port, pending writes? */
evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
void *user_data; /* Opaque pointer passed to user_callback */
struct event event; /* Read/write event */
/* circular list of replies that we want to write. */
struct server_request *pending_replies;
struct event_base *event_base;
#ifndef EVENT__DISABLE_THREAD_SUPPORT
void *lock;
#endif
};
/* Represents part of a reply being built. (That is, a single RR.) */
struct server_reply_item {
struct server_reply_item *next; /* next item in sequence. */
char *name; /* name part of the RR */
u16 type; /* The RR type */
u16 class; /* The RR class (usually CLASS_INET) */
u32 ttl; /* The RR TTL */
char is_name; /* True iff data is a label */
u16 datalen; /* Length of data; -1 if data is a label */
void *data; /* The contents of the RR */
};
/* Represents a request that we've received as a DNS server, and holds */
/* the components of the reply as we're constructing it. */
struct server_request {
/* Pointers to the next and previous entries on the list of replies */
/* that we're waiting to write. Only set if we have tried to respond */
/* and gotten EAGAIN. */
struct server_request *next_pending;
struct server_request *prev_pending;
u16 trans_id; /* Transaction id. */
struct evdns_server_port *port; /* Which port received this request on? */
struct sockaddr_storage addr; /* Where to send the response */
ev_socklen_t addrlen; /* length of addr */
int n_answer; /* how many answer RRs have been set? */
int n_authority; /* how many authority RRs have been set? */
int n_additional; /* how many additional RRs have been set? */
struct server_reply_item *answer; /* linked list of answer RRs */
struct server_reply_item *authority; /* linked list of authority RRs */
struct server_reply_item *additional; /* linked list of additional RRs */
/* Constructed response. Only set once we're ready to send a reply. */
/* Once this is set, the RR fields are cleared, and no more should be set. */
char *response;
size_t response_len;
/* Caller-visible fields: flags, questions. */
struct evdns_server_request base;
};
struct evdns_base {
/* An array of n_req_heads circular lists for inflight requests.
* Each inflight request req is in req_heads[req->trans_id % n_req_heads].
*/
struct request **req_heads;
/* A circular list of requests that we're waiting to send, but haven't
* sent yet because there are too many requests inflight */
struct request *req_waiting_head;
/* A circular list of nameservers. */
struct nameserver *server_head;
int n_req_heads;
struct event_base *event_base;
/* The number of good nameservers that we have */
int global_good_nameservers;
/* inflight requests are contained in the req_head list */
/* and are actually going out across the network */
int global_requests_inflight;
/* requests which aren't inflight are in the waiting list */
/* and are counted here */
int global_requests_waiting;
int global_max_requests_inflight;
struct timeval global_timeout; /* 5 seconds by default */
int global_max_reissues; /* a reissue occurs when we get some errors from the server */
int global_max_retransmits; /* number of times we'll retransmit a request which timed out */
/* number of timeouts in a row before we consider this server to be down */
int global_max_nameserver_timeout;
/* true iff we will use the 0x20 hack to prevent poisoning attacks. */
int global_randomize_case;
/* The first time that a nameserver fails, how long do we wait before
* probing to see if it has returned? */
struct timeval global_nameserver_probe_initial_timeout;
/** Port to bind to for outgoing DNS packets. */
struct sockaddr_storage global_outgoing_address;
/** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
ev_socklen_t global_outgoing_addrlen;
struct timeval global_getaddrinfo_allow_skew;
int getaddrinfo_ipv4_timeouts;
int getaddrinfo_ipv6_timeouts;
int getaddrinfo_ipv4_answered;
int getaddrinfo_ipv6_answered;
struct search_state *global_search_state;
TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
#ifndef EVENT__DISABLE_THREAD_SUPPORT
void *lock;
#endif
int disable_when_inactive;
};
struct hosts_entry {
TAILQ_ENTRY(hosts_entry) next;
union {
struct sockaddr sa;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
} addr;
int addrlen;
char hostname[1];
};
static struct evdns_base *current_base = NULL;
struct evdns_base *
evdns_get_global_base(void)
{
return current_base;
}
/* Given a pointer to an evdns_server_request, get the corresponding */
/* server_request. */
#define TO_SERVER_REQUEST(base_ptr) \
((struct server_request*) \
(((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
#define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
static struct nameserver *nameserver_pick(struct evdns_base *base);
static void evdns_request_insert(struct request *req, struct request **head);
static void evdns_request_remove(struct request *req, struct request **head);
static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
static int evdns_transmit(struct evdns_base *base);
static int evdns_request_transmit(struct request *req);
static void nameserver_send_probe(struct nameserver *const ns);
static void search_request_finished(struct evdns_request *const);
static int search_try_next(struct evdns_request *const req);
static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
static u16 transaction_id_pick(struct evdns_base *base);
static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
static void request_submit(struct request *const req);
static int server_request_free(struct server_request *req);
static void server_request_free_answers(struct server_request *req);
static void server_port_free(struct evdns_server_port *port);
static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
static int evdns_base_set_option_impl(struct evdns_base *base,
const char *option, const char *val, int flags);
static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
static void evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg);
static int strtoint(const char *const str);
#ifdef EVENT__DISABLE_THREAD_SUPPORT
#define EVDNS_LOCK(base) EVUTIL_NIL_STMT_
#define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
#define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
#else
#define EVDNS_LOCK(base) \
EVLOCK_LOCK((base)->lock, 0)
#define EVDNS_UNLOCK(base) \
EVLOCK_UNLOCK((base)->lock, 0)
#define ASSERT_LOCKED(base) \
EVLOCK_ASSERT_LOCKED((base)->lock)
#endif
static evdns_debug_log_fn_type evdns_log_fn = NULL;
void
evdns_set_log_fn(evdns_debug_log_fn_type fn)
{
evdns_log_fn = fn;
}
#ifdef __GNUC__
#define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
#else
#define EVDNS_LOG_CHECK
#endif
static void evdns_log_(int severity, const char *fmt, ...) EVDNS_LOG_CHECK;
static void
evdns_log_(int severity, const char *fmt, ...)
{
va_list args;
va_start(args,fmt);
if (evdns_log_fn) {
char buf[512];
int is_warn = (severity == EVDNS_LOG_WARN);
evutil_vsnprintf(buf, sizeof(buf), fmt, args);
evdns_log_fn(is_warn, buf);
} else {
event_logv_(severity, NULL, fmt, args);
}
va_end(args);
}
#define log evdns_log_
/* This walks the list of inflight requests to find the */
/* one with a matching transaction id. Returns NULL on */
/* failure */
static struct request *
request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
struct request *req = REQ_HEAD(base, trans_id);
struct request *const started_at = req;
ASSERT_LOCKED(base);
if (req) {
do {
if (req->trans_id == trans_id) return req;
req = req->next;
} while (req != started_at);
}
return NULL;
}
/* a libevent callback function which is called when a nameserver */
/* has gone down and we want to test if it has came back to life yet */
static void
nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
struct nameserver *const ns = (struct nameserver *) arg;
(void)fd;
(void)events;
EVDNS_LOCK(ns->base);
nameserver_send_probe(ns);
EVDNS_UNLOCK(ns->base);
}
/* a libevent callback which is called when a nameserver probe (to see if */
/* it has come back to life) times out. We increment the count of failed_times */
/* and wait longer to send the next probe packet. */
static void
nameserver_probe_failed(struct nameserver *const ns) {
struct timeval timeout;
int i;
ASSERT_LOCKED(ns->base);
(void) evtimer_del(&ns->timeout_event);
if (ns->state == 1) {
/* This can happen if the nameserver acts in a way which makes us mark */
/* it as bad and then starts sending good replies. */
return;
}
#define MAX_PROBE_TIMEOUT 3600
#define TIMEOUT_BACKOFF_FACTOR 3
memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
sizeof(struct timeval));
for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
if (timeout.tv_usec > 1000000) {
timeout.tv_sec += timeout.tv_usec / 1000000;
timeout.tv_usec %= 1000000;
}
}
if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
timeout.tv_sec = MAX_PROBE_TIMEOUT;
timeout.tv_usec = 0;
}
ns->failed_times++;
if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
char addrbuf[128];
log(EVDNS_LOG_WARN,
"Error from libevent when adding timer event for %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
}
}
static void
request_swap_ns(struct request *req, struct nameserver *ns) {
if (ns && req->ns != ns) {
EVUTIL_ASSERT(req->ns->requests_inflight > 0);
req->ns->requests_inflight--;
ns->requests_inflight++;
req->ns = ns;
}
}
/* called when a nameserver has been deemed to have failed. For example, too */
/* many packets have timed out etc */
static void
nameserver_failed(struct nameserver *const ns, const char *msg) {
struct request *req, *started_at;
struct evdns_base *base = ns->base;
int i;
char addrbuf[128];
ASSERT_LOCKED(base);
/* if this nameserver has already been marked as failed */
/* then don't do anything */
if (!ns->state) return;
log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)),
msg);
base->global_good_nameservers--;
EVUTIL_ASSERT(base->global_good_nameservers >= 0);
if (base->global_good_nameservers == 0) {
log(EVDNS_LOG_MSG, "All nameservers have failed");
}
ns->state = 0;
ns->failed_times = 1;
if (evtimer_add(&ns->timeout_event,
&base->global_nameserver_probe_initial_timeout) < 0) {
log(EVDNS_LOG_WARN,
"Error from libevent when adding timer event for %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
/* ???? Do more? */
}
/* walk the list of inflight requests to see if any can be reassigned to */
/* a different server. Requests in the waiting queue don't have a */
/* nameserver assigned yet */
/* if we don't have *any* good nameservers then there's no point */
/* trying to reassign requests to one */
if (!base->global_good_nameservers) return;
for (i = 0; i < base->n_req_heads; ++i) {
req = started_at = base->req_heads[i];
if (req) {
do {
if (req->tx_count == 0 && req->ns == ns) {
/* still waiting to go out, can be moved */
/* to another server */
request_swap_ns(req, nameserver_pick(base));
}
req = req->next;
} while (req != started_at);
}
}
}
static void
nameserver_up(struct nameserver *const ns)
{
char addrbuf[128];
ASSERT_LOCKED(ns->base);
if (ns->state) return;
log(EVDNS_LOG_MSG, "Nameserver %s is back up",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
evtimer_del(&ns->timeout_event);
if (ns->probe_request) {
evdns_cancel_request(ns->base, ns->probe_request);
ns->probe_request = NULL;
}
ns->state = 1;
ns->failed_times = 0;
ns->timedout = 0;
ns->base->global_good_nameservers++;
}
static void
request_trans_id_set(struct request *const req, const u16 trans_id) {
req->trans_id = trans_id;
*((u16 *) req->request) = htons(trans_id);
}
/* Called to remove a request from a list and dealloc it. */
/* head is a pointer to the head of the list it should be */
/* removed from or NULL if the request isn't in a list. */
/* when free_handle is one, free the handle as well. */
static void
request_finished(struct request *const req, struct request **head, int free_handle) {
struct evdns_base *base = req->base;
int was_inflight = (head != &base->req_waiting_head);
EVDNS_LOCK(base);
ASSERT_VALID_REQUEST(req);
if (head)
evdns_request_remove(req, head);
log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
if (was_inflight) {
evtimer_del(&req->timeout_event);
base->global_requests_inflight--;
req->ns->requests_inflight--;
} else {
base->global_requests_waiting--;
}
/* it was initialized during request_new / evtimer_assign */
event_debug_unassign(&req->timeout_event);
if (req->ns &&
req->ns->requests_inflight == 0 &&
req->base->disable_when_inactive) {
event_del(&req->ns->event);
evtimer_del(&req->ns->timeout_event);
}
if (!req->request_appended) {
/* need to free the request data on it's own */
mm_free(req->request);
} else {
/* the request data is appended onto the header */
/* so everything gets free()ed when we: */
}
if (req->handle) {
EVUTIL_ASSERT(req->handle->current_req == req);
if (free_handle) {
search_request_finished(req->handle);
req->handle->current_req = NULL;
if (! req->handle->pending_cb) {
/* If we're planning to run the callback,
* don't free the handle until later. */
mm_free(req->handle);
}
req->handle = NULL; /* If we have a bug, let's crash
* early */
} else {
req->handle->current_req = NULL;
}
}
mm_free(req);
evdns_requests_pump_waiting_queue(base);
EVDNS_UNLOCK(base);
}
/* This is called when a server returns a funny error code. */
/* We try the request again with another server. */
/* */
/* return: */
/* 0 ok */
/* 1 failed/reissue is pointless */
static int
request_reissue(struct request *req) {
const struct nameserver *const last_ns = req->ns;
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
/* the last nameserver should have been marked as failing */
/* by the caller of this function, therefore pick will try */
/* not to return it */
request_swap_ns(req, nameserver_pick(req->base));
if (req->ns == last_ns) {
/* ... but pick did return it */
/* not a lot of point in trying again with the */
/* same server */
return 1;
}
req->reissue_count++;
req->tx_count = 0;
req->transmit_me = 1;
return 0;
}
/* this function looks for space on the inflight queue and promotes */
/* requests from the waiting queue if it can. */
/* */
/* TODO: */
/* add return code, see at nameserver_pick() and other functions. */
static void
evdns_requests_pump_waiting_queue(struct evdns_base *base) {
ASSERT_LOCKED(base);
while (base->global_requests_inflight < base->global_max_requests_inflight &&
base->global_requests_waiting) {
struct request *req;
EVUTIL_ASSERT(base->req_waiting_head);
req = base->req_waiting_head;
req->ns = nameserver_pick(base);
if (!req->ns)
return;
/* move a request from the waiting queue to the inflight queue */
req->ns->requests_inflight++;
evdns_request_remove(req, &base->req_waiting_head);
base->global_requests_waiting--;
base->global_requests_inflight++;
request_trans_id_set(req, transaction_id_pick(base));
evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
evdns_request_transmit(req);
evdns_transmit(base);
}
}
/* TODO(nickm) document */
struct deferred_reply_callback {
struct event_callback deferred;
struct evdns_request *handle;
u8 request_type;
u8 have_reply;
u32 ttl;
u32 err;
evdns_callback_type user_callback;
struct reply reply;
};
static void
reply_run_callback(struct event_callback *d, void *user_pointer)
{
struct deferred_reply_callback *cb =
EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
switch (cb->request_type) {
case TYPE_A:
if (cb->have_reply)
cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
cb->reply.data.a.addrcount, cb->ttl,
cb->reply.data.a.addresses,
user_pointer);
else
cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
break;
case TYPE_PTR:
if (cb->have_reply) {
char *name = cb->reply.data.ptr.name;
cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
&name, user_pointer);
} else {
cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
}
break;
case TYPE_AAAA:
if (cb->have_reply)
cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
cb->reply.data.aaaa.addrcount, cb->ttl,
cb->reply.data.aaaa.addresses,
user_pointer);
else
cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
break;
default:
EVUTIL_ASSERT(0);
}
if (cb->handle && cb->handle->pending_cb) {
mm_free(cb->handle);
}
mm_free(cb);
}
static void
reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
{
struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
if (!d) {
event_warn("%s: Couldn't allocate space for deferred callback.",
__func__);
return;
}
ASSERT_LOCKED(req->base);
d->request_type = req->request_type;
d->user_callback = req->user_callback;
d->ttl = ttl;
d->err = err;
if (reply) {
d->have_reply = 1;
memcpy(&d->reply, reply, sizeof(struct reply));
}
if (req->handle) {
req->handle->pending_cb = 1;
d->handle = req->handle;
}
event_deferred_cb_init_(
&d->deferred,
event_get_priority(&req->timeout_event),
reply_run_callback,
req->user_pointer);
event_deferred_cb_schedule_(
req->base->event_base,
&d->deferred);
}
/* this processes a parsed reply packet */
static void
reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
int error;
char addrbuf[128];
static const int error_codes[] = {
DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
};
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (flags & 0x020f || !reply || !reply->have_answer) {
/* there was an error */
if (flags & 0x0200) {
error = DNS_ERR_TRUNCATED;
} else if (flags & 0x000f) {
u16 error_code = (flags & 0x000f) - 1;
if (error_code > 4) {
error = DNS_ERR_UNKNOWN;
} else {
error = error_codes[error_code];
}
} else if (reply && !reply->have_answer) {
error = DNS_ERR_NODATA;
} else {
error = DNS_ERR_UNKNOWN;
}
switch (error) {
case DNS_ERR_NOTIMPL:
case DNS_ERR_REFUSED:
/* we regard these errors as marking a bad nameserver */
if (req->reissue_count < req->base->global_max_reissues) {
char msg[64];
evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
error, evdns_err_to_string(error));
nameserver_failed(req->ns, msg);
if (!request_reissue(req)) return;
}
break;
case DNS_ERR_SERVERFAILED:
/* rcode 2 (servfailed) sometimes means "we
* are broken" and sometimes (with some binds)
* means "that request was very confusing."
* Treat this as a timeout, not a failure.
*/
log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
"at %s; will allow the request to time out.",
evutil_format_sockaddr_port_(
(struct sockaddr *)&req->ns->address,
addrbuf, sizeof(addrbuf)));
/* Call the timeout function */
evdns_request_timeout_callback(0, 0, req);
return;
default:
/* we got a good reply from the nameserver: it is up. */
if (req->handle == req->ns->probe_request) {
/* Avoid double-free */
req->ns->probe_request = NULL;
}
nameserver_up(req->ns);
}
if (req->handle->search_state &&
req->request_type != TYPE_PTR) {
/* if we have a list of domains to search in,
* try the next one */
if (!search_try_next(req->handle)) {
/* a new request was issued so this
* request is finished and */
/* the user callback will be made when
* that request (or a */
/* child of it) finishes. */
return;
}
}
/* all else failed. Pass the failure up */
reply_schedule_callback(req, ttl, error, NULL);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
} else {
/* all ok, tell the user */
reply_schedule_callback(req, ttl, 0, reply);
if (req->handle == req->ns->probe_request)
req->ns->probe_request = NULL; /* Avoid double-free */
nameserver_up(req->ns);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
}
}
static int
name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
int name_end = -1;
int j = *idx;
int ptr_count = 0;
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
char *cp = name_out;
const char *const end = name_out + name_out_len;
/* Normally, names are a series of length prefixed strings terminated */
/* with a length of 0 (the lengths are u8's < 63). */
/* However, the length can start with a pair of 1 bits and that */
/* means that the next 14 bits are a pointer within the current */
/* packet. */
for (;;) {
u8 label_len;
GET8(label_len);
if (!label_len) break;
if (label_len & 0xc0) {
u8 ptr_low;
GET8(ptr_low);
if (name_end < 0) name_end = j;
j = (((int)label_len & 0x3f) << 8) + ptr_low;
/* Make sure that the target offset is in-bounds. */
if (j < 0 || j >= length) return -1;
/* If we've jumped more times than there are characters in the
* message, we must have a loop. */
if (++ptr_count > length) return -1;
continue;
}
if (label_len > 63) return -1;
if (cp != name_out) {
if (cp + 1 >= end) return -1;
*cp++ = '.';
}
if (cp + label_len >= end) return -1;
if (j + label_len > length) return -1;
memcpy(cp, packet + j, label_len);
cp += label_len;
j += label_len;
}
if (cp >= end) return -1;
*cp = '\0';
if (name_end < 0)
*idx = j;
else
*idx = name_end;
return 0;
err:
return -1;
}
/* parses a raw request from a nameserver */
static int
reply_parse(struct evdns_base *base, u8 *packet, int length) {
int j = 0, k = 0; /* index into packet */
u16 t_; /* used by the macros */
u32 t32_; /* used by the macros */
char tmp_name[256], cmp_name[256]; /* used by the macros */
int name_matches = 0;
u16 trans_id, questions, answers, authority, additional, datalength;
u16 flags = 0;
u32 ttl, ttl_r = 0xffffffff;
struct reply reply;
struct request *req = NULL;
unsigned int i;
ASSERT_LOCKED(base);
GET16(trans_id);
GET16(flags);
GET16(questions);
GET16(answers);
GET16(authority);
GET16(additional);
(void) authority; /* suppress "unused variable" warnings. */
(void) additional; /* suppress "unused variable" warnings. */
req = request_find_from_trans_id(base, trans_id);
if (!req) return -1;
EVUTIL_ASSERT(req->base == base);
memset(&reply, 0, sizeof(reply));
/* If it's not an answer, it doesn't correspond to any request. */
if (!(flags & 0x8000)) return -1; /* must be an answer */
if ((flags & 0x020f) && (flags & 0x020f) != DNS_ERR_NOTEXIST) {
/* there was an error and it's not NXDOMAIN */
goto err;
}
/* if (!answers) return; */ /* must have an answer of some form */
/* This macro skips a name in the DNS reply. */
#define SKIP_NAME \
do { tmp_name[0] = '\0'; \
if (name_parse(packet, length, &j, tmp_name, \
sizeof(tmp_name))<0) \
goto err; \
} while (0)
reply.type = req->request_type;
/* skip over each question in the reply */
for (i = 0; i < questions; ++i) {
/* the question looks like
* <label:name><u16:type><u16:class>
*/
tmp_name[0] = '\0';
cmp_name[0] = '\0';
k = j;
if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name)) < 0)
goto err;
if (name_parse(req->request, req->request_len, &k,
cmp_name, sizeof(cmp_name))<0)
goto err;
if (!base->global_randomize_case) {
if (strcmp(tmp_name, cmp_name) == 0)
name_matches = 1;
} else {
if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0)
name_matches = 1;
}
j += 4;
if (j > length)
goto err;
}
if (!name_matches)
goto err;
/* now we have the answer section which looks like
* <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
*/
for (i = 0; i < answers; ++i) {
u16 type, class;
SKIP_NAME;
GET16(type);
GET16(class);
GET32(ttl);
GET16(datalength);
if (type == TYPE_A && class == CLASS_INET) {
int addrcount, addrtocopy;
if (req->request_type != TYPE_A) {
j += datalength; continue;
}
if ((datalength & 3) != 0) /* not an even number of As. */
goto err;
addrcount = datalength >> 2;
addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
ttl_r = MIN(ttl_r, ttl);
/* we only bother with the first four addresses. */
if (j + 4*addrtocopy > length) goto err;
memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
packet + j, 4*addrtocopy);
j += 4*addrtocopy;
reply.data.a.addrcount += addrtocopy;
reply.have_answer = 1;
if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
} else if (type == TYPE_PTR && class == CLASS_INET) {
if (req->request_type != TYPE_PTR) {
j += datalength; continue;
}
if (name_parse(packet, length, &j, reply.data.ptr.name,
sizeof(reply.data.ptr.name))<0)
goto err;
ttl_r = MIN(ttl_r, ttl);
reply.have_answer = 1;
break;
} else if (type == TYPE_CNAME) {
char cname[HOST_NAME_MAX];
if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
j += datalength; continue;
}
if (name_parse(packet, length, &j, cname,
sizeof(cname))<0)
goto err;
*req->put_cname_in_ptr = mm_strdup(cname);
} else if (type == TYPE_AAAA && class == CLASS_INET) {
int addrcount, addrtocopy;
if (req->request_type != TYPE_AAAA) {
j += datalength; continue;
}
if ((datalength & 15) != 0) /* not an even number of AAAAs. */
goto err;
addrcount = datalength >> 4; /* each address is 16 bytes long */
addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
ttl_r = MIN(ttl_r, ttl);
/* we only bother with the first four addresses. */
if (j + 16*addrtocopy > length) goto err;
memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
packet + j, 16*addrtocopy);
reply.data.aaaa.addrcount += addrtocopy;
j += 16*addrtocopy;
reply.have_answer = 1;
if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
} else {
/* skip over any other type of resource */
j += datalength;
}
}
if (!reply.have_answer) {
for (i = 0; i < authority; ++i) {
u16 type, class;
SKIP_NAME;
GET16(type);
GET16(class);
GET32(ttl);
GET16(datalength);
if (type == TYPE_SOA && class == CLASS_INET) {
u32 serial, refresh, retry, expire, minimum;
SKIP_NAME;
SKIP_NAME;
GET32(serial);
GET32(refresh);
GET32(retry);
GET32(expire);
GET32(minimum);
(void)expire;
(void)retry;
(void)refresh;
(void)serial;
ttl_r = MIN(ttl_r, ttl);
ttl_r = MIN(ttl_r, minimum);
} else {
/* skip over any other type of resource */
j += datalength;
}
}
}
if (ttl_r == 0xffffffff)
ttl_r = 0;
reply_handle(req, flags, ttl_r, &reply);
return 0;
err:
if (req)
reply_handle(req, flags, 0, NULL);
return -1;
}
/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
/* callback. */
static int
request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
{
int j = 0; /* index into packet */
u16 t_; /* used by the macros */
char tmp_name[256]; /* used by the macros */
int i;
u16 trans_id, flags, questions, answers, authority, additional;
struct server_request *server_req = NULL;
ASSERT_LOCKED(port);
/* Get the header fields */
GET16(trans_id);
GET16(flags);
GET16(questions);
GET16(answers);
GET16(authority);
GET16(additional);
(void)answers;
(void)additional;
(void)authority;
if (flags & 0x8000) return -1; /* Must not be an answer. */
flags &= 0x0110; /* Only RD and CD get preserved. */
server_req = mm_malloc(sizeof(struct server_request));
if (server_req == NULL) return -1;
memset(server_req, 0, sizeof(struct server_request));
server_req->trans_id = trans_id;
memcpy(&server_req->addr, addr, addrlen);
server_req->addrlen = addrlen;
server_req->base.flags = flags;
server_req->base.nquestions = 0;
server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
if (server_req->base.questions == NULL)
goto err;
for (i = 0; i < questions; ++i) {
u16 type, class;
struct evdns_server_question *q;
int namelen;
if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
goto err;
GET16(type);
GET16(class);
namelen = (int)strlen(tmp_name);
q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
if (!q)
goto err;
q->type = type;
q->dns_question_class = class;
memcpy(q->name, tmp_name, namelen+1);
server_req->base.questions[server_req->base.nquestions++] = q;
}
/* Ignore answers, authority, and additional. */
server_req->port = port;
port->refcnt++;
/* Only standard queries are supported. */
if (flags & 0x7800) {
evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
return -1;
}
port->user_callback(&(server_req->base), port->user_data);
return 0;
err:
if (server_req) {
if (server_req->base.questions) {
for (i = 0; i < server_req->base.nquestions; ++i)
mm_free(server_req->base.questions[i]);
mm_free(server_req->base.questions);
}
mm_free(server_req);
}
return -1;
#undef SKIP_NAME
#undef GET32
#undef GET16
#undef GET8
}
void
evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
{
}
void
evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
{
}
/* Try to choose a strong transaction id which isn't already in flight */
static u16
transaction_id_pick(struct evdns_base *base) {
ASSERT_LOCKED(base);
for (;;) {
u16 trans_id;
evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
if (trans_id == 0xffff) continue;
/* now check to see if that id is already inflight */
if (request_find_from_trans_id(base, trans_id) == NULL)
return trans_id;
}
}
/* choose a namesever to use. This function will try to ignore */
/* nameservers which we think are down and load balance across the rest */
/* by updating the server_head global each time. */
static struct nameserver *
nameserver_pick(struct evdns_base *base) {
struct nameserver *started_at = base->server_head, *picked;
ASSERT_LOCKED(base);
if (!base->server_head) return NULL;
/* if we don't have any good nameservers then there's no */
/* point in trying to find one. */
if (!base->global_good_nameservers) {
base->server_head = base->server_head->next;
return base->server_head;
}
/* remember that nameservers are in a circular list */
for (;;) {
if (base->server_head->state) {
/* we think this server is currently good */
picked = base->server_head;
base->server_head = base->server_head->next;
return picked;
}
base->server_head = base->server_head->next;
if (base->server_head == started_at) {
/* all the nameservers seem to be down */
/* so we just return this one and hope for the */
/* best */
EVUTIL_ASSERT(base->global_good_nameservers == 0);
picked = base->server_head;
base->server_head = base->server_head->next;
return picked;
}
}
}
/* this is called when a namesever socket is ready for reading */
static void
nameserver_read(struct nameserver *ns) {
struct sockaddr_storage ss;
ev_socklen_t addrlen = sizeof(ss);
u8 packet[1500];
char addrbuf[128];
ASSERT_LOCKED(ns->base);
for (;;) {
const int r = recvfrom(ns->socket, (void*)packet,
sizeof(packet), 0,
(struct sockaddr*)&ss, &addrlen);
if (r < 0) {
int err = evutil_socket_geterror(ns->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return;
nameserver_failed(ns,
evutil_socket_error_to_string(err));
return;
}
if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
(struct sockaddr*)&ns->address, 0)) {
log(EVDNS_LOG_WARN, "Address mismatch on received "
"DNS packet. Apparent source was %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ss,
addrbuf, sizeof(addrbuf)));
return;
}
ns->timedout = 0;
reply_parse(ns->base, packet, r);
}
}
/* Read a packet from a DNS client on a server port s, parse it, and */
/* act accordingly. */
static void
server_port_read(struct evdns_server_port *s) {
u8 packet[1500];
struct sockaddr_storage addr;
ev_socklen_t addrlen;
int r;
ASSERT_LOCKED(s);
for (;;) {
addrlen = sizeof(struct sockaddr_storage);
r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
(struct sockaddr*) &addr, &addrlen);
if (r < 0) {
int err = evutil_socket_geterror(s->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return;
log(EVDNS_LOG_WARN,
"Error %s (%d) while reading request.",
evutil_socket_error_to_string(err), err);
return;
}
request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
}
}
/* Try to write all pending replies on a given DNS server port. */
static void
server_port_flush(struct evdns_server_port *port)
{
struct server_request *req = port->pending_replies;
ASSERT_LOCKED(port);
while (req) {
int r = sendto(port->socket, req->response, (int)req->response_len, 0,
(struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
if (r < 0) {
int err = evutil_socket_geterror(port->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return;
log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
}
if (server_request_free(req)) {
/* we released the last reference to req->port. */
return;
} else {
EVUTIL_ASSERT(req != port->pending_replies);
req = port->pending_replies;
}
}
/* We have no more pending requests; stop listening for 'writeable' events. */
(void) event_del(&port->event);
event_assign(&port->event, port->event_base,
port->socket, EV_READ | EV_PERSIST,
server_port_ready_callback, port);
if (event_add(&port->event, NULL) < 0) {
log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
/* ???? Do more? */
}
}
/* set if we are waiting for the ability to write to this server. */
/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
/* we stop these events. */
static void
nameserver_write_waiting(struct nameserver *ns, char waiting) {
ASSERT_LOCKED(ns->base);
if (ns->write_waiting == waiting) return;
ns->write_waiting = waiting;
(void) event_del(&ns->event);
event_assign(&ns->event, ns->base->event_base,
ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
nameserver_ready_callback, ns);
if (event_add(&ns->event, NULL) < 0) {
char addrbuf[128];
log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
/* ???? Do more? */
}
}
/* a callback function. Called by libevent when the kernel says that */
/* a nameserver socket is ready for writing or reading */
static void
nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
struct nameserver *ns = (struct nameserver *) arg;
(void)fd;
EVDNS_LOCK(ns->base);
if (events & EV_WRITE) {
ns->choked = 0;
if (!evdns_transmit(ns->base)) {
nameserver_write_waiting(ns, 0);
}
}
if (events & EV_READ) {
nameserver_read(ns);
}
EVDNS_UNLOCK(ns->base);
}
/* a callback function. Called by libevent when the kernel says that */
/* a server socket is ready for writing or reading. */
static void
server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
struct evdns_server_port *port = (struct evdns_server_port *) arg;
(void) fd;
EVDNS_LOCK(port);
if (events & EV_WRITE) {
port->choked = 0;
server_port_flush(port);
}
if (events & EV_READ) {
server_port_read(port);
}
EVDNS_UNLOCK(port);
}
/* This is an inefficient representation; only use it via the dnslabel_table_*
* functions, so that is can be safely replaced with something smarter later. */
#define MAX_LABELS 128
/* Structures used to implement name compression */
struct dnslabel_entry { char *v; off_t pos; };
struct dnslabel_table {
int n_labels; /* number of current entries */
/* map from name to position in message */
struct dnslabel_entry labels[MAX_LABELS];
};
/* Initialize dnslabel_table. */
static void
dnslabel_table_init(struct dnslabel_table *table)
{
table->n_labels = 0;
}
/* Free all storage held by table, but not the table itself. */
static void
dnslabel_clear(struct dnslabel_table *table)
{
int i;
for (i = 0; i < table->n_labels; ++i)
mm_free(table->labels[i].v);
table->n_labels = 0;
}
/* return the position of the label in the current message, or -1 if the label */
/* hasn't been used yet. */
static int
dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
{
int i;
for (i = 0; i < table->n_labels; ++i) {
if (!strcmp(label, table->labels[i].v))
return table->labels[i].pos;
}
return -1;
}
/* remember that we've used the label at position pos */
static int
dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
{
char *v;
int p;
if (table->n_labels == MAX_LABELS)
return (-1);
v = mm_strdup(label);
if (v == NULL)
return (-1);
p = table->n_labels++;
table->labels[p].v = v;
table->labels[p].pos = pos;
return (0);
}
/* Converts a string to a length-prefixed set of DNS labels, starting */
/* at buf[j]. name and buf must not overlap. name_len should be the length */
/* of name. table is optional, and is used for compression. */
/* */
/* Input: abc.def */
/* Output: <3>abc<3>def<0> */
/* */
/* Returns the first index after the encoded name, or negative on error. */
/* -1 label was > 63 bytes */
/* -2 name too long to fit in buffer. */
/* */
static off_t
dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
const char *name, const size_t name_len,
struct dnslabel_table *table) {
const char *end = name + name_len;
int ref = 0;
u16 t_;
#define APPEND16(x) do { \
if (j + 2 > (off_t)buf_len) \
goto overflow; \
t_ = htons(x); \
memcpy(buf + j, &t_, 2); \
j += 2; \
} while (0)
#define APPEND32(x) do { \
if (j + 4 > (off_t)buf_len) \
goto overflow; \
t32_ = htonl(x); \
memcpy(buf + j, &t32_, 4); \
j += 4; \
} while (0)
if (name_len > 255) return -2;
for (;;) {
const char *const start = name;
if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
APPEND16(ref | 0xc000);
return j;
}
name = strchr(name, '.');
if (!name) {
const size_t label_len = end - start;
if (label_len > 63) return -1;
if ((size_t)(j+label_len+1) > buf_len) return -2;
if (table) dnslabel_table_add(table, start, j);
buf[j++] = (ev_uint8_t)label_len;
memcpy(buf + j, start, label_len);
j += (int) label_len;
break;
} else {
/* append length of the label. */
const size_t label_len = name - start;
if (label_len > 63) return -1;
if ((size_t)(j+label_len+1) > buf_len) return -2;
if (table) dnslabel_table_add(table, start, j);
buf[j++] = (ev_uint8_t)label_len;
memcpy(buf + j, start, label_len);
j += (int) label_len;
/* hop over the '.' */
name++;
}
}
/* the labels must be terminated by a 0. */
/* It's possible that the name ended in a . */
/* in which case the zero is already there */
if (!j || buf[j-1]) buf[j++] = 0;
return j;
overflow:
return (-2);
}
/* Finds the length of a dns request for a DNS name of the given */
/* length. The actual request may be smaller than the value returned */
/* here */
static size_t
evdns_request_len(const size_t name_len) {
return 96 + /* length of the DNS standard header */
name_len + 2 +
4; /* space for the resource type */
}
/* build a dns request packet into buf. buf should be at least as long */
/* as evdns_request_len told you it should be. */
/* */
/* Returns the amount of space used. Negative on error. */
static int
evdns_request_data_build(const char *const name, const size_t name_len,
const u16 trans_id, const u16 type, const u16 class,
u8 *const buf, size_t buf_len) {
off_t j = 0; /* current offset into buf */
u16 t_; /* used by the macros */
APPEND16(trans_id);
APPEND16(0x0100); /* standard query, recusion needed */
APPEND16(1); /* one question */
APPEND16(0); /* no answers */
APPEND16(0); /* no authority */
APPEND16(0); /* no additional */
j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
if (j < 0) {
return (int)j;
}
APPEND16(type);
APPEND16(class);
return (int)j;
overflow:
return (-1);
}
/* exported function */
struct evdns_server_port *
evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
{
struct evdns_server_port *port;
if (flags)
return NULL; /* flags not yet implemented */
if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
return NULL;
memset(port, 0, sizeof(struct evdns_server_port));
port->socket = socket;
port->refcnt = 1;
port->choked = 0;
port->closing = 0;
port->user_callback = cb;
port->user_data = user_data;
port->pending_replies = NULL;
port->event_base = base;
event_assign(&port->event, port->event_base,
port->socket, EV_READ | EV_PERSIST,
server_port_ready_callback, port);
if (event_add(&port->event, NULL) < 0) {
mm_free(port);
return NULL;
}
EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
return port;
}
struct evdns_server_port *
evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
{
return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
}
/* exported function */
void
evdns_close_server_port(struct evdns_server_port *port)
{
EVDNS_LOCK(port);
if (--port->refcnt == 0) {
EVDNS_UNLOCK(port);
server_port_free(port);
} else {
port->closing = 1;
}
}
/* exported function */
int
evdns_server_request_add_reply(struct evdns_server_request *req_, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
struct server_reply_item **itemp, *item;
int *countp;
int result = -1;
EVDNS_LOCK(req->port);
if (req->response) /* have we already answered? */
goto done;
switch (section) {
case EVDNS_ANSWER_SECTION:
itemp = &req->answer;
countp = &req->n_answer;
break;
case EVDNS_AUTHORITY_SECTION:
itemp = &req->authority;
countp = &req->n_authority;
break;
case EVDNS_ADDITIONAL_SECTION:
itemp = &req->additional;
countp = &req->n_additional;
break;
default:
goto done;
}
while (*itemp) {
itemp = &((*itemp)->next);
}
item = mm_malloc(sizeof(struct server_reply_item));
if (!item)
goto done;
item->next = NULL;
if (!(item->name = mm_strdup(name))) {
mm_free(item);
goto done;
}
item->type = type;
item->dns_question_class = class;
item->ttl = ttl;
item->is_name = is_name != 0;
item->datalen = 0;
item->data = NULL;
if (data) {
if (item->is_name) {
if (!(item->data = mm_strdup(data))) {
mm_free(item->name);
mm_free(item);
goto done;
}
item->datalen = (u16)-1;
} else {
if (!(item->data = mm_malloc(datalen))) {
mm_free(item->name);
mm_free(item);
goto done;
}
item->datalen = datalen;
memcpy(item->data, data, datalen);
}
}
*itemp = item;
++(*countp);
result = 0;
done:
EVDNS_UNLOCK(req->port);
return result;
}
/* exported function */
int
evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
{
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
ttl, n*4, 0, addrs);
}
/* exported function */
int
evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
{
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
ttl, n*16, 0, addrs);
}
/* exported function */
int
evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
{
u32 a;
char buf[32];
if (in && inaddr_name)
return -1;
else if (!in && !inaddr_name)
return -1;
if (in) {
a = ntohl(in->s_addr);
evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
(int)(u8)((a )&0xff),
(int)(u8)((a>>8 )&0xff),
(int)(u8)((a>>16)&0xff),
(int)(u8)((a>>24)&0xff));
inaddr_name = buf;
}
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
ttl, -1, 1, hostname);
}
/* exported function */
int
evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
{
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
ttl, -1, 1, cname);
}
/* exported function */
void
evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
{
struct server_request *req = TO_SERVER_REQUEST(exreq);
req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
req->base.flags |= flags;
}
static int
evdns_server_request_format_response(struct server_request *req, int err)
{
unsigned char buf[1500];
size_t buf_len = sizeof(buf);
off_t j = 0, r;
u16 t_;
u32 t32_;
int i;
u16 flags;
struct dnslabel_table table;
if (err < 0 || err > 15) return -1;
/* Set response bit and error code; copy OPCODE and RD fields from
* question; copy RA and AA if set by caller. */
flags = req->base.flags;
flags |= (0x8000 | err);
dnslabel_table_init(&table);
APPEND16(req->trans_id);
APPEND16(flags);
APPEND16(req->base.nquestions);
APPEND16(req->n_answer);
APPEND16(req->n_authority);
APPEND16(req->n_additional);
/* Add questions. */
for (i=0; i < req->base.nquestions; ++i) {
const char *s = req->base.questions[i]->name;
j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
if (j < 0) {
dnslabel_clear(&table);
return (int) j;
}
APPEND16(req->base.questions[i]->type);
APPEND16(req->base.questions[i]->dns_question_class);
}
/* Add answer, authority, and additional sections. */
for (i=0; i<3; ++i) {
struct server_reply_item *item;
if (i==0)
item = req->answer;
else if (i==1)
item = req->authority;
else
item = req->additional;
while (item) {
r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
if (r < 0)
goto overflow;
j = r;
APPEND16(item->type);
APPEND16(item->dns_question_class);
APPEND32(item->ttl);
if (item->is_name) {
off_t len_idx = j, name_start;
j += 2;
name_start = j;
r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
if (r < 0)
goto overflow;
j = r;
t_ = htons( (short) (j-name_start) );
memcpy(buf+len_idx, &t_, 2);
} else {
APPEND16(item->datalen);
if (j+item->datalen > (off_t)buf_len)
goto overflow;
memcpy(buf+j, item->data, item->datalen);
j += item->datalen;
}
item = item->next;
}
}
if (j > 512) {
overflow:
j = 512;
buf[2] |= 0x02; /* set the truncated bit. */
}
req->response_len = j;
if (!(req->response = mm_malloc(req->response_len))) {
server_request_free_answers(req);
dnslabel_clear(&table);
return (-1);
}
memcpy(req->response, buf, req->response_len);
server_request_free_answers(req);
dnslabel_clear(&table);
return (0);
}
/* exported function */
int
evdns_server_request_respond(struct evdns_server_request *req_, int err)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
struct evdns_server_port *port = req->port;
int r = -1;
EVDNS_LOCK(port);
if (!req->response) {
if ((r = evdns_server_request_format_response(req, err))<0)
goto done;
}
r = sendto(port->socket, req->response, (int)req->response_len, 0,
(struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
if (r<0) {
int sock_err = evutil_socket_geterror(port->socket);
if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
goto done;
if (port->pending_replies) {
req->prev_pending = port->pending_replies->prev_pending;
req->next_pending = port->pending_replies;
req->prev_pending->next_pending =
req->next_pending->prev_pending = req;
} else {
req->prev_pending = req->next_pending = req;
port->pending_replies = req;
port->choked = 1;
(void) event_del(&port->event);
event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
if (event_add(&port->event, NULL) < 0) {
log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
}
}
r = 1;
goto done;
}
if (server_request_free(req)) {
r = 0;
goto done;
}
if (port->pending_replies)
server_port_flush(port);
r = 0;
done:
EVDNS_UNLOCK(port);
return r;
}
/* Free all storage held by RRs in req. */
static void
server_request_free_answers(struct server_request *req)
{
struct server_reply_item *victim, *next, **list;
int i;
for (i = 0; i < 3; ++i) {
if (i==0)
list = &req->answer;
else if (i==1)
list = &req->authority;
else
list = &req->additional;
victim = *list;
while (victim) {
next = victim->next;
mm_free(victim->name);
if (victim->data)
mm_free(victim->data);
mm_free(victim);
victim = next;
}
*list = NULL;
}
}
/* Free all storage held by req, and remove links to it. */
/* return true iff we just wound up freeing the server_port. */
static int
server_request_free(struct server_request *req)
{
int i, rc=1, lock=0;
if (req->base.questions) {
for (i = 0; i < req->base.nquestions; ++i)
mm_free(req->base.questions[i]);
mm_free(req->base.questions);
}
if (req->port) {
EVDNS_LOCK(req->port);
lock=1;
if (req->port->pending_replies == req) {
if (req->next_pending && req->next_pending != req)
req->port->pending_replies = req->next_pending;
else
req->port->pending_replies = NULL;
}
rc = --req->port->refcnt;
}
if (req->response) {
mm_free(req->response);
}
server_request_free_answers(req);
if (req->next_pending && req->next_pending != req) {
req->next_pending->prev_pending = req->prev_pending;
req->prev_pending->next_pending = req->next_pending;
}
if (rc == 0) {
EVDNS_UNLOCK(req->port); /* ????? nickm */
server_port_free(req->port);
mm_free(req);
return (1);
}
if (lock)
EVDNS_UNLOCK(req->port);
mm_free(req);
return (0);
}
/* Free all storage held by an evdns_server_port. Only called when */
static void
server_port_free(struct evdns_server_port *port)
{
EVUTIL_ASSERT(port);
EVUTIL_ASSERT(!port->refcnt);
EVUTIL_ASSERT(!port->pending_replies);
if (port->socket > 0) {
evutil_closesocket(port->socket);
port->socket = -1;
}
(void) event_del(&port->event);
event_debug_unassign(&port->event);
EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
mm_free(port);
}
/* exported function */
int
evdns_server_request_drop(struct evdns_server_request *req_)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
server_request_free(req);
return 0;
}
/* exported function */
int
evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
if (addr_len < (int)req->addrlen)
return -1;
memcpy(sa, &(req->addr), req->addrlen);
return req->addrlen;
}
#undef APPEND16
#undef APPEND32
/* this is a libevent callback function which is called when a request */
/* has timed out. */
static void
evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
struct request *const req = (struct request *) arg;
struct evdns_base *base = req->base;
(void) fd;
(void) events;
log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
EVDNS_LOCK(base);
if (req->tx_count >= req->base->global_max_retransmits) {
struct nameserver *ns = req->ns;
/* this request has failed */
log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
arg, req->tx_count);
reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
nameserver_failed(ns, "request timed out.");
} else {
/* retransmit it */
log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
arg, req->tx_count);
(void) evtimer_del(&req->timeout_event);
request_swap_ns(req, nameserver_pick(base));
evdns_request_transmit(req);
req->ns->timedout++;
if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
req->ns->timedout = 0;
nameserver_failed(req->ns, "request timed out.");
}
}
EVDNS_UNLOCK(base);
}
/* try to send a request to a given server. */
/* */
/* return: */
/* 0 ok */
/* 1 temporary failure */
/* 2 other failure */
static int
evdns_request_transmit_to(struct request *req, struct nameserver *server) {
int r;
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (server->requests_inflight == 1 &&
req->base->disable_when_inactive &&
event_add(&server->event, NULL) < 0) {
return 1;
}
r = sendto(server->socket, (void*)req->request, req->request_len, 0,
(struct sockaddr *)&server->address, server->addrlen);
if (r < 0) {
int err = evutil_socket_geterror(server->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return 1;
nameserver_failed(req->ns, evutil_socket_error_to_string(err));
return 2;
} else if (r != (int)req->request_len) {
return 1; /* short write */
} else {
return 0;
}
}
/* try to send a request, updating the fields of the request */
/* as needed */
/* */
/* return: */
/* 0 ok */
/* 1 failed */
static int
evdns_request_transmit(struct request *req) {
int retcode = 0, r;
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
/* if we fail to send this packet then this flag marks it */
/* for evdns_transmit */
req->transmit_me = 1;
EVUTIL_ASSERT(req->trans_id != 0xffff);
if (!req->ns)
{
/* unable to transmit request if no nameservers */
return 1;
}
if (req->ns->choked) {
/* don't bother trying to write to a socket */
/* which we have had EAGAIN from */
return 1;
}
r = evdns_request_transmit_to(req, req->ns);
switch (r) {
case 1:
/* temp failure */
req->ns->choked = 1;
nameserver_write_waiting(req->ns, 1);
return 1;
case 2:
/* failed to transmit the request entirely. */
retcode = 1;
/* fall through: we'll set a timeout, which will time out,
* and make us retransmit the request anyway. */
default:
/* all ok */
log(EVDNS_LOG_DEBUG,
"Setting timeout for request %p, sent to nameserver %p", req, req->ns);
if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
log(EVDNS_LOG_WARN,
"Error from libevent when adding timer for request %p",
req);
/* ???? Do more? */
}
req->tx_count++;
req->transmit_me = 0;
return retcode;
}
}
static void
nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
struct nameserver *const ns = (struct nameserver *) arg;
(void) type;
(void) count;
(void) ttl;
(void) addresses;
if (result == DNS_ERR_CANCEL) {
/* We canceled this request because the nameserver came up
* for some other reason. Do not change our opinion about
* the nameserver. */
return;
}
EVDNS_LOCK(ns->base);
ns->probe_request = NULL;
if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
/* this is a good reply */
nameserver_up(ns);
} else {
nameserver_probe_failed(ns);
}
EVDNS_UNLOCK(ns->base);
}
static void
nameserver_send_probe(struct nameserver *const ns) {
struct evdns_request *handle;
struct request *req;
char addrbuf[128];
/* here we need to send a probe to a given nameserver */
/* in the hope that it is up now. */
ASSERT_LOCKED(ns->base);
log(EVDNS_LOG_DEBUG, "Sending probe to %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
handle = mm_calloc(1, sizeof(*handle));
if (!handle) return;
req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
if (!req) {
mm_free(handle);
return;
}
ns->probe_request = handle;
/* we force this into the inflight queue no matter what */
request_trans_id_set(req, transaction_id_pick(ns->base));
req->ns = ns;
request_submit(req);
}
/* returns: */
/* 0 didn't try to transmit anything */
/* 1 tried to transmit something */
static int
evdns_transmit(struct evdns_base *base) {
char did_try_to_transmit = 0;
int i;
ASSERT_LOCKED(base);
for (i = 0; i < base->n_req_heads; ++i) {
if (base->req_heads[i]) {
struct request *const started_at = base->req_heads[i], *req = started_at;
/* first transmit all the requests which are currently waiting */
do {
if (req->transmit_me) {
did_try_to_transmit = 1;
evdns_request_transmit(req);
}
req = req->next;
} while (req != started_at);
}
}
return did_try_to_transmit;
}
/* exported function */
int
evdns_base_count_nameservers(struct evdns_base *base)
{
const struct nameserver *server;
int n = 0;
EVDNS_LOCK(base);
server = base->server_head;
if (!server)
goto done;
do {
++n;
server = server->next;
} while (server != base->server_head);
done:
EVDNS_UNLOCK(base);
return n;
}
int
evdns_count_nameservers(void)
{
return evdns_base_count_nameservers(current_base);
}
/* exported function */
int
evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
{
struct nameserver *server, *started_at;
int i;
EVDNS_LOCK(base);
server = base->server_head;
started_at = base->server_head;
if (!server) {
EVDNS_UNLOCK(base);
return 0;
}
while (1) {
struct nameserver *next = server->next;
(void) event_del(&server->event);
if (evtimer_initialized(&server->timeout_event))
(void) evtimer_del(&server->timeout_event);
if (server->probe_request) {
evdns_cancel_request(server->base, server->probe_request);
server->probe_request = NULL;
}
if (server->socket >= 0)
evutil_closesocket(server->socket);
mm_free(server);
if (next == started_at)
break;
server = next;
}
base->server_head = NULL;
base->global_good_nameservers = 0;
for (i = 0; i < base->n_req_heads; ++i) {
struct request *req, *req_started_at;
req = req_started_at = base->req_heads[i];
while (req) {
struct request *next = req->next;
req->tx_count = req->reissue_count = 0;
req->ns = NULL;
/* ???? What to do about searches? */
(void) evtimer_del(&req->timeout_event);
req->trans_id = 0;
req->transmit_me = 0;
base->global_requests_waiting++;
evdns_request_insert(req, &base->req_waiting_head);
/* We want to insert these suspended elements at the front of
* the waiting queue, since they were pending before any of
* the waiting entries were added. This is a circular list,
* so we can just shift the start back by one.*/
base->req_waiting_head = base->req_waiting_head->prev;
if (next == req_started_at)
break;
req = next;
}
base->req_heads[i] = NULL;
}
base->global_requests_inflight = 0;
EVDNS_UNLOCK(base);
return 0;
}
int
evdns_clear_nameservers_and_suspend(void)
{
return evdns_base_clear_nameservers_and_suspend(current_base);
}
/* exported function */
int
evdns_base_resume(struct evdns_base *base)
{
EVDNS_LOCK(base);
evdns_requests_pump_waiting_queue(base);
EVDNS_UNLOCK(base);
return 0;
}
int
evdns_resume(void)
{
return evdns_base_resume(current_base);
}
static int
evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
/* first check to see if we already have this nameserver */
const struct nameserver *server = base->server_head, *const started_at = base->server_head;
struct nameserver *ns;
int err = 0;
char addrbuf[128];
ASSERT_LOCKED(base);
if (server) {
do {
if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
server = server->next;
} while (server != started_at);
}
if (addrlen > (int)sizeof(ns->address)) {
log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
return 2;
}
ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
if (!ns) return -1;
memset(ns, 0, sizeof(struct nameserver));
ns->base = base;
evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
ns->socket = evutil_socket_(address->sa_family,
SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
if (ns->socket < 0) { err = 1; goto out1; }
if (base->global_outgoing_addrlen &&
!evutil_sockaddr_is_loopback_(address)) {
if (bind(ns->socket,
(struct sockaddr*)&base->global_outgoing_address,
base->global_outgoing_addrlen) < 0) {
log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
err = 2;
goto out2;
}
}
memcpy(&ns->address, address, addrlen);
ns->addrlen = addrlen;
ns->state = 1;
event_assign(&ns->event, ns->base->event_base, ns->socket,
EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
if (!base->disable_when_inactive && event_add(&ns->event, NULL) < 0) {
err = 2;
goto out2;
}
log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
/* insert this nameserver into the list of them */
if (!base->server_head) {
ns->next = ns->prev = ns;
base->server_head = ns;
} else {
ns->next = base->server_head->next;
ns->prev = base->server_head;
base->server_head->next = ns;
ns->next->prev = ns;
}
base->global_good_nameservers++;
return 0;
out2:
evutil_closesocket(ns->socket);
out1:
event_debug_unassign(&ns->event);
mm_free(ns);
log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
return err;
}
/* exported function */
int
evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
{
struct sockaddr_in sin;
int res;
memset(&sin, 0, sizeof(sin));
sin.sin_addr.s_addr = address;
sin.sin_port = htons(53);
sin.sin_family = AF_INET;
EVDNS_LOCK(base);
res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
EVDNS_UNLOCK(base);
return res;
}
int
evdns_nameserver_add(unsigned long int address) {
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_nameserver_add(current_base, address);
}
static void
sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
{
if (sa->sa_family == AF_INET) {
((struct sockaddr_in *)sa)->sin_port = htons(port);
} else if (sa->sa_family == AF_INET6) {
((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
}
}
static ev_uint16_t
sockaddr_getport(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return ntohs(((struct sockaddr_in *)sa)->sin_port);
} else if (sa->sa_family == AF_INET6) {
return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
} else {
return 0;
}
}
/* exported function */
int
evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
struct sockaddr_storage ss;
struct sockaddr *sa;
int len = sizeof(ss);
int res;
if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
&len)) {
log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
ip_as_string);
return 4;
}
sa = (struct sockaddr *) &ss;
if (sockaddr_getport(sa) == 0)
sockaddr_setport(sa, 53);
EVDNS_LOCK(base);
res = evdns_nameserver_add_impl_(base, sa, len);
EVDNS_UNLOCK(base);
return res;
}
int
evdns_nameserver_ip_add(const char *ip_as_string) {
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_nameserver_ip_add(current_base, ip_as_string);
}
int
evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
{
int res;
EVUTIL_ASSERT(base);
EVDNS_LOCK(base);
res = evdns_nameserver_add_impl_(base, sa, len);
EVDNS_UNLOCK(base);
return res;
}
int
evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
struct sockaddr *sa, ev_socklen_t len)
{
int result = -1;
int i;
struct nameserver *server;
EVDNS_LOCK(base);
server = base->server_head;
for (i = 0; i < idx && server; ++i, server = server->next) {
if (server->next == base->server_head)
goto done;
}
if (! server)
goto done;
if (server->addrlen > len) {
result = (int) server->addrlen;
goto done;
}
memcpy(sa, &server->address, server->addrlen);
result = (int) server->addrlen;
done:
EVDNS_UNLOCK(base);
return result;
}
/* remove from the queue */
static void
evdns_request_remove(struct request *req, struct request **head)
{
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
#if 0
{
struct request *ptr;
int found = 0;
EVUTIL_ASSERT(*head != NULL);
ptr = *head;
do {
if (ptr == req) {
found = 1;
break;
}
ptr = ptr->next;
} while (ptr != *head);
EVUTIL_ASSERT(found);
EVUTIL_ASSERT(req->next);
}
#endif
if (req->next == req) {
/* only item in the list */
*head = NULL;
} else {
req->next->prev = req->prev;
req->prev->next = req->next;
if (*head == req) *head = req->next;
}
req->next = req->prev = NULL;
}
/* insert into the tail of the queue */
static void
evdns_request_insert(struct request *req, struct request **head) {
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (!*head) {
*head = req;
req->next = req->prev = req;
return;
}
req->prev = (*head)->prev;
req->prev->next = req;
req->next = *head;
(*head)->prev = req;
}
static int
string_num_dots(const char *s) {
int count = 0;
while ((s = strchr(s, '.'))) {
s++;
count++;
}
return count;
}
static struct request *
request_new(struct evdns_base *base, struct evdns_request *handle, int type,
const char *name, int flags, evdns_callback_type callback,
void *user_ptr) {
const char issuing_now =
(base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
const size_t name_len = strlen(name);
const size_t request_max_len = evdns_request_len(name_len);
const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
/* the request data is alloced in a single block with the header */
struct request *const req =
mm_malloc(sizeof(struct request) + request_max_len);
int rlen;
char namebuf[256];
(void) flags;
ASSERT_LOCKED(base);
if (!req) return NULL;
if (name_len >= sizeof(namebuf)) {
mm_free(req);
return NULL;
}
memset(req, 0, sizeof(struct request));
req->base = base;
evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
if (base->global_randomize_case) {
unsigned i;
char randbits[(sizeof(namebuf)+7)/8];
strlcpy(namebuf, name, sizeof(namebuf));
evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
for (i = 0; i < name_len; ++i) {
if (EVUTIL_ISALPHA_(namebuf[i])) {
if ((randbits[i >> 3] & (1<<(i & 7))))
namebuf[i] |= 0x20;
else
namebuf[i] &= ~0x20;
}
}
name = namebuf;
}
/* request data lives just after the header */
req->request = ((u8 *) req) + sizeof(struct request);
/* denotes that the request data shouldn't be free()ed */
req->request_appended = 1;
rlen = evdns_request_data_build(name, name_len, trans_id,
type, CLASS_INET, req->request, request_max_len);
if (rlen < 0)
goto err1;
req->request_len = rlen;
req->trans_id = trans_id;
req->tx_count = 0;
req->request_type = type;
req->user_pointer = user_ptr;
req->user_callback = callback;
req->ns = issuing_now ? nameserver_pick(base) : NULL;
req->next = req->prev = NULL;
req->handle = handle;
if (handle) {
handle->current_req = req;
handle->base = base;
}
return req;
err1:
mm_free(req);
return NULL;
}
static void
request_submit(struct request *const req) {
struct evdns_base *base = req->base;
ASSERT_LOCKED(base);
ASSERT_VALID_REQUEST(req);
if (req->ns) {
/* if it has a nameserver assigned then this is going */
/* straight into the inflight queue */
evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
base->global_requests_inflight++;
req->ns->requests_inflight++;
evdns_request_transmit(req);
} else {
evdns_request_insert(req, &base->req_waiting_head);
base->global_requests_waiting++;
}
}
/* exported function */
void
evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
{
struct request *req;
if (!handle->current_req)
return;
if (!base) {
/* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
base = handle->base;
if (!base)
base = handle->current_req->base;
}
EVDNS_LOCK(base);
if (handle->pending_cb) {
EVDNS_UNLOCK(base);
return;
}
req = handle->current_req;
ASSERT_VALID_REQUEST(req);
reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
if (req->ns) {
/* remove from inflight queue */
request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
} else {
/* remove from global_waiting head */
request_finished(req, &base->req_waiting_head, 1);
}
EVDNS_UNLOCK(base);
}
/* exported function */
struct evdns_request *
evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
evdns_callback_type callback, void *ptr) {
struct evdns_request *handle;
struct request *req;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
EVDNS_LOCK(base);
if (flags & DNS_QUERY_NO_SEARCH) {
req =
request_new(base, handle, TYPE_A, name, flags,
callback, ptr);
if (req)
request_submit(req);
} else {
search_request_new(base, handle, TYPE_A, name, flags,
callback, ptr);
}
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return handle;
}
int evdns_resolve_ipv4(const char *name, int flags,
evdns_callback_type callback, void *ptr)
{
return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
? 0 : -1;
}
/* exported function */
struct evdns_request *
evdns_base_resolve_ipv6(struct evdns_base *base,
const char *name, int flags,
evdns_callback_type callback, void *ptr)
{
struct evdns_request *handle;
struct request *req;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
EVDNS_LOCK(base);
if (flags & DNS_QUERY_NO_SEARCH) {
req = request_new(base, handle, TYPE_AAAA, name, flags,
callback, ptr);
if (req)
request_submit(req);
} else {
search_request_new(base, handle, TYPE_AAAA, name, flags,
callback, ptr);
}
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return handle;
}
int evdns_resolve_ipv6(const char *name, int flags,
evdns_callback_type callback, void *ptr) {
return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
? 0 : -1;
}
struct evdns_request *
evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
char buf[32];
struct evdns_request *handle;
struct request *req;
u32 a;
EVUTIL_ASSERT(in);
a = ntohl(in->s_addr);
evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
(int)(u8)((a )&0xff),
(int)(u8)((a>>8 )&0xff),
(int)(u8)((a>>16)&0xff),
(int)(u8)((a>>24)&0xff));
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
EVDNS_LOCK(base);
req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
if (req)
request_submit(req);
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return (handle);
}
int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
? 0 : -1;
}
struct evdns_request *
evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
/* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
char buf[73];
char *cp;
struct evdns_request *handle;
struct request *req;
int i;
EVUTIL_ASSERT(in);
cp = buf;
for (i=15; i >= 0; --i) {
u8 byte = in->s6_addr[i];
*cp++ = "0123456789abcdef"[byte & 0x0f];
*cp++ = '.';
*cp++ = "0123456789abcdef"[byte >> 4];
*cp++ = '.';
}
EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
EVDNS_LOCK(base);
req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
if (req)
request_submit(req);
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return (handle);
}
int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
? 0 : -1;
}
/* ================================================================= */
/* Search support */
/* */
/* the libc resolver has support for searching a number of domains */
/* to find a name. If nothing else then it takes the single domain */
/* from the gethostname() call. */
/* */
/* It can also be configured via the domain and search options in a */
/* resolv.conf. */
/* */
/* The ndots option controls how many dots it takes for the resolver */
/* to decide that a name is non-local and so try a raw lookup first. */
struct search_domain {
int len;
struct search_domain *next;
/* the text string is appended to this structure */
};
struct search_state {
int refcount;
int ndots;
int num_domains;
struct search_domain *head;
};
static void
search_state_decref(struct search_state *const state) {
if (!state) return;
state->refcount--;
if (!state->refcount) {
struct search_domain *next, *dom;
for (dom = state->head; dom; dom = next) {
next = dom->next;
mm_free(dom);
}
mm_free(state);
}
}
static struct search_state *
search_state_new(void) {
struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
if (!state) return NULL;
memset(state, 0, sizeof(struct search_state));
state->refcount = 1;
state->ndots = 1;
return state;
}
static void
search_postfix_clear(struct evdns_base *base) {
search_state_decref(base->global_search_state);
base->global_search_state = search_state_new();
}
/* exported function */
void
evdns_base_search_clear(struct evdns_base *base)
{
EVDNS_LOCK(base);
search_postfix_clear(base);
EVDNS_UNLOCK(base);
}
void
evdns_search_clear(void) {
evdns_base_search_clear(current_base);
}
static void
search_postfix_add(struct evdns_base *base, const char *domain) {
size_t domain_len;
struct search_domain *sdomain;
while (domain[0] == '.') domain++;
domain_len = strlen(domain);
ASSERT_LOCKED(base);
if (!base->global_search_state) base->global_search_state = search_state_new();
if (!base->global_search_state) return;
base->global_search_state->num_domains++;
sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
if (!sdomain) return;
memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
sdomain->next = base->global_search_state->head;
sdomain->len = (int) domain_len;
base->global_search_state->head = sdomain;
}
/* reverse the order of members in the postfix list. This is needed because, */
/* when parsing resolv.conf we push elements in the wrong order */
static void
search_reverse(struct evdns_base *base) {
struct search_domain *cur, *prev = NULL, *next;
ASSERT_LOCKED(base);
cur = base->global_search_state->head;
while (cur) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
base->global_search_state->head = prev;
}
/* exported function */
void
evdns_base_search_add(struct evdns_base *base, const char *domain) {
EVDNS_LOCK(base);
search_postfix_add(base, domain);
EVDNS_UNLOCK(base);
}
void
evdns_search_add(const char *domain) {
evdns_base_search_add(current_base, domain);
}
/* exported function */
void
evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
EVDNS_LOCK(base);
if (!base->global_search_state) base->global_search_state = search_state_new();
if (base->global_search_state)
base->global_search_state->ndots = ndots;
EVDNS_UNLOCK(base);
}
void
evdns_search_ndots_set(const int ndots) {
evdns_base_search_ndots_set(current_base, ndots);
}
static void
search_set_from_hostname(struct evdns_base *base) {
char hostname[HOST_NAME_MAX + 1], *domainname;
ASSERT_LOCKED(base);
search_postfix_clear(base);
if (gethostname(hostname, sizeof(hostname))) return;
domainname = strchr(hostname, '.');
if (!domainname) return;
search_postfix_add(base, domainname);
}
/* warning: returns malloced string */
static char *
search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
struct search_domain *dom;
for (dom = state->head; dom; dom = dom->next) {
if (!n--) {
/* this is the postfix we want */
/* the actual postfix string is kept at the end of the structure */
const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
const int postfix_len = dom->len;
char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
if (!newname) return NULL;
memcpy(newname, base_name, base_len);
if (need_to_append_dot) newname[base_len] = '.';
memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
newname[base_len + need_to_append_dot + postfix_len] = 0;
return newname;
}
}
/* we ran off the end of the list and still didn't find the requested string */
EVUTIL_ASSERT(0);
return NULL; /* unreachable; stops warnings in some compilers. */
}
static struct request *
search_request_new(struct evdns_base *base, struct evdns_request *handle,
int type, const char *const name, int flags,
evdns_callback_type user_callback, void *user_arg) {
ASSERT_LOCKED(base);
EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
EVUTIL_ASSERT(handle->current_req == NULL);
if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
base->global_search_state &&
base->global_search_state->num_domains) {
/* we have some domains to search */
struct request *req;
if (string_num_dots(name) >= base->global_search_state->ndots) {
req = request_new(base, handle, type, name, flags, user_callback, user_arg);
if (!req) return NULL;
handle->search_index = -1;
} else {
char *const new_name = search_make_new(base->global_search_state, 0, name);
if (!new_name) return NULL;
req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
mm_free(new_name);
if (!req) return NULL;
handle->search_index = 0;
}
EVUTIL_ASSERT(handle->search_origname == NULL);
handle->search_origname = mm_strdup(name);
if (handle->search_origname == NULL) {
/* XXX Should we dealloc req? If yes, how? */
if (req)
mm_free(req);
return NULL;
}
handle->search_state = base->global_search_state;
handle->search_flags = flags;
base->global_search_state->refcount++;
request_submit(req);
return req;
} else {
struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
if (!req) return NULL;
request_submit(req);
return req;
}
}
/* this is called when a request has failed to find a name. We need to check */
/* if it is part of a search and, if so, try the next name in the list */
/* returns: */
/* 0 another request has been submitted */
/* 1 no more requests needed */
static int
search_try_next(struct evdns_request *const handle) {
struct request *req = handle->current_req;
struct evdns_base *base = req->base;
struct request *newreq;
ASSERT_LOCKED(base);
if (handle->search_state) {
/* it is part of a search */
char *new_name;
handle->search_index++;
if (handle->search_index >= handle->search_state->num_domains) {
/* no more postfixes to try, however we may need to try */
/* this name without a postfix */
if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
/* yep, we need to try it raw */
newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
if (newreq) {
search_request_finished(handle);
goto submit_next;
}
}
return 1;
}
new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
if (!new_name) return 1;
log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
mm_free(new_name);
if (!newreq) return 1;
goto submit_next;
}
return 1;
submit_next:
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
handle->current_req = newreq;
newreq->handle = handle;
request_submit(newreq);
return 0;
}
static void
search_request_finished(struct evdns_request *const handle) {
ASSERT_LOCKED(handle->current_req->base);
if (handle->search_state) {
search_state_decref(handle->search_state);
handle->search_state = NULL;
}
if (handle->search_origname) {
mm_free(handle->search_origname);
handle->search_origname = NULL;
}
}
/* ================================================================= */
/* Parsing resolv.conf files */
static void
evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
/* if the file isn't found then we assume a local resolver */
ASSERT_LOCKED(base);
if (flags & DNS_OPTION_SEARCH) search_set_from_hostname(base);
if (flags & DNS_OPTION_NAMESERVERS) evdns_base_nameserver_ip_add(base,"127.0.0.1");
}
#ifndef EVENT__HAVE_STRTOK_R
static char *
strtok_r(char *s, const char *delim, char **state) {
char *cp, *start;
start = cp = s ? s : *state;
if (!cp)
return NULL;
while (*cp && !strchr(delim, *cp))
++cp;
if (!*cp) {
if (cp == start)
return NULL;
*state = NULL;
return start;
} else {
*cp++ = '\0';
*state = cp;
return start;
}
}
#endif
/* helper version of atoi which returns -1 on error */
static int
strtoint(const char *const str)
{
char *endptr;
const int r = strtol(str, &endptr, 10);
if (*endptr) return -1;
return r;
}
/* Parse a number of seconds into a timeval; return -1 on error. */
static int
evdns_strtotimeval(const char *const str, struct timeval *out)
{
double d;
char *endptr;
d = strtod(str, &endptr);
if (*endptr) return -1;
if (d < 0) return -1;
out->tv_sec = (int) d;
out->tv_usec = (int) ((d - (int) d)*1000000);
if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
return -1;
return 0;
}
/* helper version of atoi that returns -1 on error and clips to bounds. */
static int
strtoint_clipped(const char *const str, int min, int max)
{
int r = strtoint(str);
if (r == -1)
return r;
else if (r<min)
return min;
else if (r>max)
return max;
else
return r;
}
static int
evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
{
int old_n_heads = base->n_req_heads, n_heads;
struct request **old_heads = base->req_heads, **new_heads, *req;
int i;
ASSERT_LOCKED(base);
if (maxinflight < 1)
maxinflight = 1;
n_heads = (maxinflight+4) / 5;
EVUTIL_ASSERT(n_heads > 0);
new_heads = mm_calloc(n_heads, sizeof(struct request*));
if (!new_heads)
return (-1);
if (old_heads) {
for (i = 0; i < old_n_heads; ++i) {
while (old_heads[i]) {
req = old_heads[i];
evdns_request_remove(req, &old_heads[i]);
evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
}
}
mm_free(old_heads);
}
base->req_heads = new_heads;
base->n_req_heads = n_heads;
base->global_max_requests_inflight = maxinflight;
return (0);
}
/* exported function */
int
evdns_base_set_option(struct evdns_base *base,
const char *option, const char *val)
{
int res;
EVDNS_LOCK(base);
res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
EVDNS_UNLOCK(base);
return res;
}
static inline int
str_matches_option(const char *s1, const char *optionname)
{
/* Option names are given as "option:" We accept either 'option' in
* s1, or 'option:randomjunk'. The latter form is to implement the
* resolv.conf parser. */
size_t optlen = strlen(optionname);
size_t slen = strlen(s1);
if (slen == optlen || slen == optlen - 1)
return !strncmp(s1, optionname, slen);
else if (slen > optlen)
return !strncmp(s1, optionname, optlen);
else
return 0;
}
static int
evdns_base_set_option_impl(struct evdns_base *base,
const char *option, const char *val, int flags)
{
ASSERT_LOCKED(base);
if (str_matches_option(option, "ndots:")) {
const int ndots = strtoint(val);
if (ndots == -1) return -1;
if (!(flags & DNS_OPTION_SEARCH)) return 0;
log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
if (!base->global_search_state) base->global_search_state = search_state_new();
if (!base->global_search_state) return -1;
base->global_search_state->ndots = ndots;
} else if (str_matches_option(option, "timeout:")) {
struct timeval tv;
if (evdns_strtotimeval(val, &tv) == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
} else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
struct timeval tv;
if (evdns_strtotimeval(val, &tv) == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
val);
memcpy(&base->global_getaddrinfo_allow_skew, &tv,
sizeof(struct timeval));
} else if (str_matches_option(option, "max-timeouts:")) {
const int maxtimeout = strtoint_clipped(val, 1, 255);
if (maxtimeout == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
maxtimeout);
base->global_max_nameserver_timeout = maxtimeout;
} else if (str_matches_option(option, "max-inflight:")) {
const int maxinflight = strtoint_clipped(val, 1, 65000);
if (maxinflight == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
maxinflight);
evdns_base_set_max_requests_inflight(base, maxinflight);
} else if (str_matches_option(option, "attempts:")) {
int retries = strtoint(val);
if (retries == -1) return -1;
if (retries > 255) retries = 255;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
base->global_max_retransmits = retries;
} else if (str_matches_option(option, "randomize-case:")) {
int randcase = strtoint(val);
if (!(flags & DNS_OPTION_MISC)) return 0;
base->global_randomize_case = randcase;
} else if (str_matches_option(option, "bind-to:")) {
/* XXX This only applies to successive nameservers, not
* to already-configured ones. We might want to fix that. */
int len = sizeof(base->global_outgoing_address);
if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
if (evutil_parse_sockaddr_port(val,
(struct sockaddr*)&base->global_outgoing_address, &len))
return -1;
base->global_outgoing_addrlen = len;
} else if (str_matches_option(option, "initial-probe-timeout:")) {
struct timeval tv;
if (evdns_strtotimeval(val, &tv) == -1) return -1;
if (tv.tv_sec > 3600)
tv.tv_sec = 3600;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
val);
memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
sizeof(tv));
}
return 0;
}
int
evdns_set_option(const char *option, const char *val, int flags)
{
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_set_option(current_base, option, val);
}
static void
resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
char *strtok_state;
static const char *const delims = " \t";
#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
char *const first_token = strtok_r(start, delims, &strtok_state);
ASSERT_LOCKED(base);
if (!first_token) return;
if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
const char *const nameserver = NEXT_TOKEN;
if (nameserver)
evdns_base_nameserver_ip_add(base, nameserver);
} else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
const char *const domain = NEXT_TOKEN;
if (domain) {
search_postfix_clear(base);
search_postfix_add(base, domain);
}
} else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
const char *domain;
search_postfix_clear(base);
while ((domain = NEXT_TOKEN)) {
search_postfix_add(base, domain);
}
search_reverse(base);
} else if (!strcmp(first_token, "options")) {
const char *option;
while ((option = NEXT_TOKEN)) {
const char *val = strchr(option, ':');
evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
}
}
#undef NEXT_TOKEN
}
/* exported function */
/* returns: */
/* 0 no errors */
/* 1 failed to open file */
/* 2 failed to stat file */
/* 3 file too large */
/* 4 out of memory */
/* 5 short read from file */
int
evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
int res;
EVDNS_LOCK(base);
res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
EVDNS_UNLOCK(base);
return res;
}
static char *
evdns_get_default_hosts_filename(void)
{
#ifdef _WIN32
/* Windows is a little coy about where it puts its configuration
* files. Sure, they're _usually_ in C:\windows\system32, but
* there's no reason in principle they couldn't be in
* W:\hoboken chicken emergency\
*/
char path[MAX_PATH+1];
static const char hostfile[] = "\\drivers\\etc\\hosts";
char *path_out;
size_t len_out;
if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
return NULL;
len_out = strlen(path)+strlen(hostfile)+1;
path_out = mm_malloc(len_out);
evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
return path_out;
#else
return mm_strdup("/etc/hosts");
#endif
}
static int
evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
size_t n;
char *resolv;
char *start;
int err = 0;
log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
if (flags & DNS_OPTION_HOSTSFILE) {
char *fname = evdns_get_default_hosts_filename();
evdns_base_load_hosts(base, fname);
if (fname)
mm_free(fname);
}
if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
if (err == -1) {
/* No file. */
evdns_resolv_set_defaults(base, flags);
return 1;
} else {
return 2;
}
}
start = resolv;
for (;;) {
char *const newline = strchr(start, '\n');
if (!newline) {
resolv_conf_parse_line(base, start, flags);
break;
} else {
*newline = 0;
resolv_conf_parse_line(base, start, flags);
start = newline + 1;
}
}
if (!base->server_head && (flags & DNS_OPTION_NAMESERVERS)) {
/* no nameservers were configured. */
evdns_base_nameserver_ip_add(base, "127.0.0.1");
err = 6;
}
if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
search_set_from_hostname(base);
}
mm_free(resolv);
return err;
}
int
evdns_resolv_conf_parse(int flags, const char *const filename) {
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_resolv_conf_parse(current_base, flags, filename);
}
#ifdef _WIN32
/* Add multiple nameservers from a space-or-comma-separated list. */
static int
evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
const char *addr;
char *buf;
int r;
ASSERT_LOCKED(base);
while (*ips) {
while (isspace(*ips) || *ips == ',' || *ips == '\t')
++ips;
addr = ips;
while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
*ips=='[' || *ips==']')
++ips;
buf = mm_malloc(ips-addr+1);
if (!buf) return 4;
memcpy(buf, addr, ips-addr);
buf[ips-addr] = '\0';
r = evdns_base_nameserver_ip_add(base, buf);
mm_free(buf);
if (r) return r;
}
return 0;
}
typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
/* figure out what our nameservers are. */
static int
load_nameservers_with_getnetworkparams(struct evdns_base *base)
{
/* Based on MSDN examples and inspection of c-ares code. */
FIXED_INFO *fixed;
HMODULE handle = 0;
ULONG size = sizeof(FIXED_INFO);
void *buf = NULL;
int status = 0, r, added_any;
IP_ADDR_STRING *ns;
GetNetworkParams_fn_t fn;
ASSERT_LOCKED(base);
if (!(handle = evutil_load_windows_system_library_(
TEXT("iphlpapi.dll")))) {
log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
status = -1;
goto done;
}
if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
log(EVDNS_LOG_WARN, "Could not get address of function.");
status = -1;
goto done;
}
buf = mm_malloc(size);
if (!buf) { status = 4; goto done; }
fixed = buf;
r = fn(fixed, &size);
if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
status = -1;
goto done;
}
if (r != ERROR_SUCCESS) {
mm_free(buf);
buf = mm_malloc(size);
if (!buf) { status = 4; goto done; }
fixed = buf;
r = fn(fixed, &size);
if (r != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG, "fn() failed.");
status = -1;
goto done;
}
}
EVUTIL_ASSERT(fixed);
added_any = 0;
ns = &(fixed->DnsServerList);
while (ns) {
r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
if (r) {
log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
(ns->IpAddress.String),(int)GetLastError());
status = r;
} else {
++added_any;
log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
}
ns = ns->Next;
}
if (!added_any) {
log(EVDNS_LOG_DEBUG, "No nameservers added.");
if (status == 0)
status = -1;
} else {
status = 0;
}
done:
if (buf)
mm_free(buf);
if (handle)
FreeLibrary(handle);
return status;
}
static int
config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
{
char *buf;
DWORD bufsz = 0, type = 0;
int status = 0;
ASSERT_LOCKED(base);
if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
!= ERROR_MORE_DATA)
return -1;
if (!(buf = mm_malloc(bufsz)))
return -1;
if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
== ERROR_SUCCESS && bufsz > 1) {
status = evdns_nameserver_ip_add_line(base,buf);
}
mm_free(buf);
return status;
}
#define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
#define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
#define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
static int
load_nameservers_from_registry(struct evdns_base *base)
{
int found = 0;
int r;
#define TRY(k, name) \
if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
found = 1; \
} else if (!found) { \
log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
#k,#name); \
}
ASSERT_LOCKED(base);
if (((int)GetVersion()) > 0) { /* NT */
HKEY nt_key = 0, interfaces_key = 0;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
KEY_READ, &nt_key) != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
return -1;
}
r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
&interfaces_key);
if (r != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
return -1;
}
TRY(nt_key, "NameServer");
TRY(nt_key, "DhcpNameServer");
TRY(interfaces_key, "NameServer");
TRY(interfaces_key, "DhcpNameServer");
RegCloseKey(interfaces_key);
RegCloseKey(nt_key);
} else {
HKEY win_key = 0;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
KEY_READ, &win_key) != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
return -1;
}
TRY(win_key, "NameServer");
RegCloseKey(win_key);
}
if (found == 0) {
log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
}
return found ? 0 : -1;
#undef TRY
}
int
evdns_base_config_windows_nameservers(struct evdns_base *base)
{
int r;
char *fname;
if (base == NULL)
base = current_base;
if (base == NULL)
return -1;
EVDNS_LOCK(base);
fname = evdns_get_default_hosts_filename();
log(EVDNS_LOG_DEBUG, "Loading hosts entries from %s", fname);
evdns_base_load_hosts(base, fname);
if (fname)
mm_free(fname);
if (load_nameservers_with_getnetworkparams(base) == 0) {
EVDNS_UNLOCK(base);
return 0;
}
r = load_nameservers_from_registry(base);
EVDNS_UNLOCK(base);
return r;
}
int
evdns_config_windows_nameservers(void)
{
if (!current_base) {
current_base = evdns_base_new(NULL, 1);
return current_base == NULL ? -1 : 0;
} else {
return evdns_base_config_windows_nameservers(current_base);
}
}
#endif
struct evdns_base *
evdns_base_new(struct event_base *event_base, int flags)
{
struct evdns_base *base;
if (evutil_secure_rng_init() < 0) {
log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
"DNS can't run.");
return NULL;
}
/* Give the evutil library a hook into its evdns-enabled
* functionality. We can't just call evdns_getaddrinfo directly or
* else libevent-core will depend on libevent-extras. */
evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
base = mm_malloc(sizeof(struct evdns_base));
if (base == NULL)
return (NULL);
memset(base, 0, sizeof(struct evdns_base));
base->req_waiting_head = NULL;
EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
EVDNS_LOCK(base);
/* Set max requests inflight and allocate req_heads. */
base->req_heads = NULL;
evdns_base_set_max_requests_inflight(base, 64);
base->server_head = NULL;
base->event_base = event_base;
base->global_good_nameservers = base->global_requests_inflight =
base->global_requests_waiting = 0;
base->global_timeout.tv_sec = 5;
base->global_timeout.tv_usec = 0;
base->global_max_reissues = 1;
base->global_max_retransmits = 3;
base->global_max_nameserver_timeout = 3;
base->global_search_state = NULL;
base->global_randomize_case = 1;
base->global_getaddrinfo_allow_skew.tv_sec = 3;
base->global_getaddrinfo_allow_skew.tv_usec = 0;
base->global_nameserver_probe_initial_timeout.tv_sec = 10;
base->global_nameserver_probe_initial_timeout.tv_usec = 0;
TAILQ_INIT(&base->hostsdb);
#define EVDNS_BASE_ALL_FLAGS (0x8001)
if (flags & ~EVDNS_BASE_ALL_FLAGS) {
flags = EVDNS_BASE_INITIALIZE_NAMESERVERS;
log(EVDNS_LOG_WARN,
"Unrecognized flag passed to evdns_base_new(). Assuming "
"you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
}
#undef EVDNS_BASE_ALL_FLAGS
if (flags & EVDNS_BASE_INITIALIZE_NAMESERVERS) {
int r;
#ifdef _WIN32
r = evdns_base_config_windows_nameservers(base);
#else
r = evdns_base_resolv_conf_parse(base, DNS_OPTIONS_ALL, "/etc/resolv.conf");
#endif
if (r == -1) {
evdns_base_free_and_unlock(base, 0);
return NULL;
}
}
if (flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE) {
base->disable_when_inactive = 1;
}
EVDNS_UNLOCK(base);
return base;
}
int
evdns_init(void)
{
struct evdns_base *base = evdns_base_new(NULL, 1);
if (base) {
current_base = base;
return 0;
} else {
return -1;
}
}
const char *
evdns_err_to_string(int err)
{
switch (err) {
case DNS_ERR_NONE: return "no error";
case DNS_ERR_FORMAT: return "misformatted query";
case DNS_ERR_SERVERFAILED: return "server failed";
case DNS_ERR_NOTEXIST: return "name does not exist";
case DNS_ERR_NOTIMPL: return "query not implemented";
case DNS_ERR_REFUSED: return "refused";
case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
case DNS_ERR_UNKNOWN: return "unknown";
case DNS_ERR_TIMEOUT: return "request timed out";
case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
case DNS_ERR_CANCEL: return "dns request canceled";
case DNS_ERR_NODATA: return "no records in the reply";
default: return "[Unknown error code]";
}
}
static void
evdns_nameserver_free(struct nameserver *server)
{
if (server->socket >= 0)
evutil_closesocket(server->socket);
(void) event_del(&server->event);
event_debug_unassign(&server->event);
if (server->state == 0)
(void) event_del(&server->timeout_event);
if (server->probe_request) {
evdns_cancel_request(server->base, server->probe_request);
server->probe_request = NULL;
}
event_debug_unassign(&server->timeout_event);
mm_free(server);
}
static void
evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
{
struct nameserver *server, *server_next;
struct search_domain *dom, *dom_next;
int i;
/* Requires that we hold the lock. */
/* TODO(nickm) we might need to refcount here. */
for (i = 0; i < base->n_req_heads; ++i) {
while (base->req_heads[i]) {
if (fail_requests)
reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
}
}
while (base->req_waiting_head) {
if (fail_requests)
reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
}
base->global_requests_inflight = base->global_requests_waiting = 0;
for (server = base->server_head; server; server = server_next) {
server_next = server->next;
evdns_nameserver_free(server);
if (server_next == base->server_head)
break;
}
base->server_head = NULL;
base->global_good_nameservers = 0;
if (base->global_search_state) {
for (dom = base->global_search_state->head; dom; dom = dom_next) {
dom_next = dom->next;
mm_free(dom);
}
mm_free(base->global_search_state);
base->global_search_state = NULL;
}
{
struct hosts_entry *victim;
while ((victim = TAILQ_FIRST(&base->hostsdb))) {
TAILQ_REMOVE(&base->hostsdb, victim, next);
mm_free(victim);
}
}
mm_free(base->req_heads);
EVDNS_UNLOCK(base);
EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
mm_free(base);
}
void
evdns_base_free(struct evdns_base *base, int fail_requests)
{
EVDNS_LOCK(base);
evdns_base_free_and_unlock(base, fail_requests);
}
void
evdns_base_clear_host_addresses(struct evdns_base *base)
{
struct hosts_entry *victim;
EVDNS_LOCK(base);
while ((victim = TAILQ_FIRST(&base->hostsdb))) {
TAILQ_REMOVE(&base->hostsdb, victim, next);
mm_free(victim);
}
EVDNS_UNLOCK(base);
}
void
evdns_shutdown(int fail_requests)
{
if (current_base) {
struct evdns_base *b = current_base;
current_base = NULL;
evdns_base_free(b, fail_requests);
}
evdns_log_fn = NULL;
}
static int
evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
{
char *strtok_state;
static const char *const delims = " \t";
char *const addr = strtok_r(line, delims, &strtok_state);
char *hostname, *hash;
struct sockaddr_storage ss;
int socklen = sizeof(ss);
ASSERT_LOCKED(base);
#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
if (!addr || *addr == '#')
return 0;
memset(&ss, 0, sizeof(ss));
if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
return -1;
if (socklen > (int)sizeof(struct sockaddr_in6))
return -1;
if (sockaddr_getport((struct sockaddr*)&ss))
return -1;
while ((hostname = NEXT_TOKEN)) {
struct hosts_entry *he;
size_t namelen;
if ((hash = strchr(hostname, '#'))) {
if (hash == hostname)
return 0;
*hash = '\0';
}
namelen = strlen(hostname);
he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
if (!he)
return -1;
EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
memcpy(&he->addr, &ss, socklen);
memcpy(he->hostname, hostname, namelen+1);
he->addrlen = socklen;
TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
if (hash)
return 0;
}
return 0;
#undef NEXT_TOKEN
}
static int
evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
{
char *str=NULL, *cp, *eol;
size_t len;
int err=0;
ASSERT_LOCKED(base);
if (hosts_fname == NULL ||
(err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
char tmp[64];
strlcpy(tmp, "127.0.0.1 localhost", sizeof(tmp));
evdns_base_parse_hosts_line(base, tmp);
strlcpy(tmp, "::1 localhost", sizeof(tmp));
evdns_base_parse_hosts_line(base, tmp);
return err ? -1 : 0;
}
/* This will break early if there is a NUL in the hosts file.
* Probably not a problem.*/
cp = str;
for (;;) {
eol = strchr(cp, '\n');
if (eol) {
*eol = '\0';
evdns_base_parse_hosts_line(base, cp);
cp = eol+1;
} else {
evdns_base_parse_hosts_line(base, cp);
break;
}
}
mm_free(str);
return 0;
}
int
evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
{
int res;
if (!base)
base = current_base;
EVDNS_LOCK(base);
res = evdns_base_load_hosts_impl(base, hosts_fname);
EVDNS_UNLOCK(base);
return res;
}
/* A single request for a getaddrinfo, either v4 or v6. */
struct getaddrinfo_subrequest {
struct evdns_request *r;
ev_uint32_t type;
};
/* State data used to implement an in-progress getaddrinfo. */
struct evdns_getaddrinfo_request {
struct evdns_base *evdns_base;
/* Copy of the modified 'hints' data that we'll use to build
* answers. */
struct evutil_addrinfo hints;
/* The callback to invoke when we're done */
evdns_getaddrinfo_cb user_cb;
/* User-supplied data to give to the callback. */
void *user_data;
/* The port to use when building sockaddrs. */
ev_uint16_t port;
/* The sub_request for an A record (if any) */
struct getaddrinfo_subrequest ipv4_request;
/* The sub_request for an AAAA record (if any) */
struct getaddrinfo_subrequest ipv6_request;
/* The cname result that we were told (if any) */
char *cname_result;
/* If we have one request answered and one request still inflight,
* then this field holds the answer from the first request... */
struct evutil_addrinfo *pending_result;
/* And this event is a timeout that will tell us to cancel the second
* request if it's taking a long time. */
struct event timeout;
/* And this field holds the error code from the first request... */
int pending_error;
/* If this is set, the user canceled this request. */
unsigned user_canceled : 1;
/* If this is set, the user can no longer cancel this request; we're
* just waiting for the free. */
unsigned request_done : 1;
};
/* Convert an evdns errors to the equivalent getaddrinfo error. */
static int
evdns_err_to_getaddrinfo_err(int e1)
{
/* XXX Do this better! */
if (e1 == DNS_ERR_NONE)
return 0;
else if (e1 == DNS_ERR_NOTEXIST)
return EVUTIL_EAI_NONAME;
else
return EVUTIL_EAI_FAIL;
}
/* Return the more informative of two getaddrinfo errors. */
static int
getaddrinfo_merge_err(int e1, int e2)
{
/* XXXX be cleverer here. */
if (e1 == 0)
return e2;
else
return e1;
}
static void
free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
{
/* DO NOT CALL this if either of the requests is pending. Only once
* both callbacks have been invoked is it safe to free the request */
if (data->pending_result)
evutil_freeaddrinfo(data->pending_result);
if (data->cname_result)
mm_free(data->cname_result);
event_del(&data->timeout);
mm_free(data);
return;
}
static void
add_cname_to_reply(struct evdns_getaddrinfo_request *data,
struct evutil_addrinfo *ai)
{
if (data->cname_result && ai) {
ai->ai_canonname = data->cname_result;
data->cname_result = NULL;
}
}
/* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
* request has finished, but the other one took too long to answer. Pass
* along the answer we got, and cancel the other request.
*/
static void
evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
{
int v4_timedout = 0, v6_timedout = 0;
struct evdns_getaddrinfo_request *data = ptr;
/* Cancel any pending requests, and note which one */
if (data->ipv4_request.r) {
/* XXXX This does nothing if the request's callback is already
* running (pending_cb is set). */
evdns_cancel_request(NULL, data->ipv4_request.r);
v4_timedout = 1;
EVDNS_LOCK(data->evdns_base);
++data->evdns_base->getaddrinfo_ipv4_timeouts;
EVDNS_UNLOCK(data->evdns_base);
}
if (data->ipv6_request.r) {
/* XXXX This does nothing if the request's callback is already
* running (pending_cb is set). */
evdns_cancel_request(NULL, data->ipv6_request.r);
v6_timedout = 1;
EVDNS_LOCK(data->evdns_base);
++data->evdns_base->getaddrinfo_ipv6_timeouts;
EVDNS_UNLOCK(data->evdns_base);
}
/* We only use this timeout callback when we have an answer for
* one address. */
EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
/* Report the outcome of the other request that didn't time out. */
if (data->pending_result) {
add_cname_to_reply(data, data->pending_result);
data->user_cb(0, data->pending_result, data->user_data);
data->pending_result = NULL;
} else {
int e = data->pending_error;
if (!e)
e = EVUTIL_EAI_AGAIN;
data->user_cb(e, NULL, data->user_data);
}
data->user_cb = NULL; /* prevent double-call if evdns callbacks are
* in-progress. XXXX It would be better if this
* weren't necessary. */
if (!v4_timedout && !v6_timedout) {
/* should be impossible? XXXX */
free_getaddrinfo_request(data);
}
}
static int
evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
struct evdns_getaddrinfo_request *data)
{
return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
}
static inline int
evdns_result_is_answer(int result)
{
return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
}
static void
evdns_getaddrinfo_gotresolve(int result, char type, int count,
int ttl, void *addresses, void *arg)
{
int i;
struct getaddrinfo_subrequest *req = arg;
struct getaddrinfo_subrequest *other_req;
struct evdns_getaddrinfo_request *data;
struct evutil_addrinfo *res;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
struct sockaddr *sa;
int socklen, addrlen;
void *addrp;
int err;
int user_canceled;
EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
if (req->type == DNS_IPv4_A) {
data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
other_req = &data->ipv6_request;
} else {
data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
other_req = &data->ipv4_request;
}
/** Called from evdns_base_free() with @fail_requests == 1 */
if (result != DNS_ERR_SHUTDOWN) {
EVDNS_LOCK(data->evdns_base);
if (evdns_result_is_answer(result)) {
if (req->type == DNS_IPv4_A)
++data->evdns_base->getaddrinfo_ipv4_answered;
else
++data->evdns_base->getaddrinfo_ipv6_answered;
}
user_canceled = data->user_canceled;
if (other_req->r == NULL)
data->request_done = 1;
EVDNS_UNLOCK(data->evdns_base);
} else {
data->evdns_base = NULL;
user_canceled = data->user_canceled;
}
req->r = NULL;
if (result == DNS_ERR_CANCEL && ! user_canceled) {
/* Internal cancel request from timeout or internal error.
* we already answered the user. */
if (other_req->r == NULL)
free_getaddrinfo_request(data);
return;
}
if (data->user_cb == NULL) {
/* We already answered. XXXX This shouldn't be needed; see
* comments in evdns_getaddrinfo_timeout_cb */
free_getaddrinfo_request(data);
return;
}
if (result == DNS_ERR_NONE) {
if (count == 0)
err = EVUTIL_EAI_NODATA;
else
err = 0;
} else {
err = evdns_err_to_getaddrinfo_err(result);
}
if (err) {
/* Looks like we got an error. */
if (other_req->r) {
/* The other request is still working; maybe it will
* succeed. */
/* XXXX handle failure from set_timeout */
if (result != DNS_ERR_SHUTDOWN) {
evdns_getaddrinfo_set_timeout(data->evdns_base, data);
}
data->pending_error = err;
return;
}
if (user_canceled) {
data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
} else if (data->pending_result) {
/* If we have an answer waiting, and we weren't
* canceled, ignore this error. */
add_cname_to_reply(data, data->pending_result);
data->user_cb(0, data->pending_result, data->user_data);
data->pending_result = NULL;
} else {
if (data->pending_error)
err = getaddrinfo_merge_err(err,
data->pending_error);
data->user_cb(err, NULL, data->user_data);
}
free_getaddrinfo_request(data);
return;
} else if (user_canceled) {
if (other_req->r) {
/* The other request is still working; let it hit this
* callback with EVUTIL_EAI_CANCEL callback and report
* the failure. */
return;
}
data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
free_getaddrinfo_request(data);
return;
}
/* Looks like we got some answers. We should turn them into addrinfos
* and then either queue those or return them all. */
EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
if (type == DNS_IPv4_A) {
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(data->port);
sa = (struct sockaddr *)&sin;
socklen = sizeof(sin);
addrlen = 4;
addrp = &sin.sin_addr.s_addr;
} else {
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(data->port);
sa = (struct sockaddr *)&sin6;
socklen = sizeof(sin6);
addrlen = 16;
addrp = &sin6.sin6_addr.s6_addr;
}
res = NULL;
for (i=0; i < count; ++i) {
struct evutil_addrinfo *ai;
memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
if (!ai) {
if (other_req->r) {
evdns_cancel_request(NULL, other_req->r);
}
data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
if (res)
evutil_freeaddrinfo(res);
if (other_req->r == NULL)
free_getaddrinfo_request(data);
return;
}
res = evutil_addrinfo_append_(res, ai);
}
if (other_req->r) {
/* The other request is still in progress; wait for it */
/* XXXX handle failure from set_timeout */
evdns_getaddrinfo_set_timeout(data->evdns_base, data);
data->pending_result = res;
return;
} else {
/* The other request is done or never started; append its
* results (if any) and return them. */
if (data->pending_result) {
if (req->type == DNS_IPv4_A)
res = evutil_addrinfo_append_(res,
data->pending_result);
else
res = evutil_addrinfo_append_(
data->pending_result, res);
data->pending_result = NULL;
}
/* Call the user callback. */
add_cname_to_reply(data, res);
data->user_cb(0, res, data->user_data);
/* Free data. */
free_getaddrinfo_request(data);
}
}
static struct hosts_entry *
find_hosts_entry(struct evdns_base *base, const char *hostname,
struct hosts_entry *find_after)
{
struct hosts_entry *e;
if (find_after)
e = TAILQ_NEXT(find_after, next);
else
e = TAILQ_FIRST(&base->hostsdb);
for (; e; e = TAILQ_NEXT(e, next)) {
if (!evutil_ascii_strcasecmp(e->hostname, hostname))
return e;
}
return NULL;
}
static int
evdns_getaddrinfo_fromhosts(struct evdns_base *base,
const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
struct evutil_addrinfo **res)
{
int n_found = 0;
struct hosts_entry *e;
struct evutil_addrinfo *ai=NULL;
int f = hints->ai_family;
EVDNS_LOCK(base);
for (e = find_hosts_entry(base, nodename, NULL); e;
e = find_hosts_entry(base, nodename, e)) {
struct evutil_addrinfo *ai_new;
++n_found;
if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
(e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
continue;
ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
if (!ai_new) {
n_found = 0;
goto out;
}
sockaddr_setport(ai_new->ai_addr, port);
ai = evutil_addrinfo_append_(ai, ai_new);
}
EVDNS_UNLOCK(base);
out:
if (n_found) {
/* Note that we return an empty answer if we found entries for
* this hostname but none were of the right address type. */
*res = ai;
return 0;
} else {
if (ai)
evutil_freeaddrinfo(ai);
return -1;
}
}
struct evdns_getaddrinfo_request *
evdns_getaddrinfo(struct evdns_base *dns_base,
const char *nodename, const char *servname,
const struct evutil_addrinfo *hints_in,
evdns_getaddrinfo_cb cb, void *arg)
{
struct evdns_getaddrinfo_request *data;
struct evutil_addrinfo hints;
struct evutil_addrinfo *res = NULL;
int err;
int port = 0;
int want_cname = 0;
if (!dns_base) {
dns_base = current_base;
if (!dns_base) {
log(EVDNS_LOG_WARN,
"Call to getaddrinfo_async with no "
"evdns_base configured.");
cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
return NULL;
}
}
/* If we _must_ answer this immediately, do so. */
if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
res = NULL;
err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
cb(err, res, arg);
return NULL;
}
if (hints_in) {
memcpy(&hints, hints_in, sizeof(hints));
} else {
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
}
evutil_adjust_hints_for_addrconfig_(&hints);
/* Now try to see if we _can_ answer immediately. */
/* (It would be nice to do this by calling getaddrinfo directly, with
* AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
* a reliable way to distinguish the "that wasn't a numeric host!" case
* from any other EAI_NONAME cases.) */
err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
if (err != EVUTIL_EAI_NEED_RESOLVE) {
cb(err, res, arg);
return NULL;
}
/* If there is an entry in the hosts file, we should give it now. */
if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
cb(0, res, arg);
return NULL;
}
/* Okay, things are serious now. We're going to need to actually
* launch a request.
*/
data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
if (!data) {
cb(EVUTIL_EAI_MEMORY, NULL, arg);
return NULL;
}
memcpy(&data->hints, &hints, sizeof(data->hints));
data->port = (ev_uint16_t)port;
data->ipv4_request.type = DNS_IPv4_A;
data->ipv6_request.type = DNS_IPv6_AAAA;
data->user_cb = cb;
data->user_data = arg;
data->evdns_base = dns_base;
want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
/* If we are asked for a PF_UNSPEC address, we launch two requests in
* parallel: one for an A address and one for an AAAA address. We
* can't send just one request, since many servers only answer one
* question per DNS request.
*
* Once we have the answer to one request, we allow for a short
* timeout before we report it, to see if the other one arrives. If
* they both show up in time, then we report both the answers.
*
* If too many addresses of one type time out or fail, we should stop
* launching those requests. (XXX we don't do that yet.)
*/
if (hints.ai_family != PF_INET6) {
log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
nodename, &data->ipv4_request);
data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
nodename, 0, evdns_getaddrinfo_gotresolve,
&data->ipv4_request);
if (want_cname && data->ipv4_request.r)
data->ipv4_request.r->current_req->put_cname_in_ptr =
&data->cname_result;
}
if (hints.ai_family != PF_INET) {
log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
nodename, &data->ipv6_request);
data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
nodename, 0, evdns_getaddrinfo_gotresolve,
&data->ipv6_request);
if (want_cname && data->ipv6_request.r)
data->ipv6_request.r->current_req->put_cname_in_ptr =
&data->cname_result;
}
evtimer_assign(&data->timeout, dns_base->event_base,
evdns_getaddrinfo_timeout_cb, data);
if (data->ipv4_request.r || data->ipv6_request.r) {
return data;
} else {
mm_free(data);
cb(EVUTIL_EAI_FAIL, NULL, arg);
return NULL;
}
}
void
evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
{
EVDNS_LOCK(data->evdns_base);
if (data->request_done) {
EVDNS_UNLOCK(data->evdns_base);
return;
}
event_del(&data->timeout);
data->user_canceled = 1;
if (data->ipv4_request.r)
evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
if (data->ipv6_request.r)
evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
EVDNS_UNLOCK(data->evdns_base);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4838_0 |
crossvul-cpp_data_good_1282_1 | /*
* This file includes functions to transform a concrete syntax tree (CST) to
* an abstract syntax tree (AST). The main function is Ta27AST_FromNode().
*
*/
#include "Python.h"
#include "Python-ast.h"
#include "grammar.h"
#include "node.h"
#include "pyarena.h"
#include "ast.h"
#include "token.h"
#include "parsetok.h"
#include "graminit.h"
#include "unicodeobject.h"
#include <assert.h>
/* Data structure used internally */
struct compiling {
char *c_encoding; /* source encoding */
int c_future_unicode; /* __future__ unicode literals flag */
PyArena *c_arena; /* arena for allocating memeory */
const char *c_filename; /* filename */
};
static asdl_seq *seq_for_testlist(struct compiling *, const node *);
static expr_ty ast_for_expr(struct compiling *, const node *);
static stmt_ty ast_for_stmt(struct compiling *, const node *);
static asdl_seq *ast_for_suite(struct compiling *, const node *);
static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
expr_context_ty);
static expr_ty ast_for_testlist(struct compiling *, const node *);
static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
static expr_ty ast_for_testlist_comp(struct compiling *, const node *);
/* Note different signature for ast_for_call */
static expr_ty ast_for_call(struct compiling *, const node *, expr_ty);
static PyObject *parsenumber(struct compiling *, const char *);
static PyObject *parsestr(struct compiling *, const node *n, const char *);
static PyObject *parsestrplus(struct compiling *, const node *n);
static int Py_Py3kWarningFlag = 0;
static int Py_UnicodeFlag = 0;
extern long Ta27OS_strtol(char *str, char **ptr, int base);
#ifndef LINENO
#define LINENO(n) ((n)->n_lineno)
#endif
#define COMP_GENEXP 0
#define COMP_SETCOMP 1
static identifier
new_identifier(const char* n, PyArena *arena) {
PyObject* id = PyUnicode_InternFromString(n);
if (id != NULL)
PyArena_AddPyObject(arena, id);
return id;
}
#define NEW_IDENTIFIER(n) new_identifier(STR(n), c->c_arena)
static string
new_type_comment(const char *s, struct compiling *c)
{
return PyUnicode_DecodeUTF8(s, strlen(s), NULL);
}
#define NEW_TYPE_COMMENT(n) new_type_comment(STR(n), c)
/* This routine provides an invalid object for the syntax error.
The outermost routine must unpack this error and create the
proper object. We do this so that we don't have to pass
the filename to everything function.
XXX Maybe we should just pass the filename...
*/
static int
ast_error(const node *n, const char *errstr)
{
PyObject *u = Py_BuildValue("zi", errstr, LINENO(n));
if (!u)
return 0;
PyErr_SetObject(PyExc_SyntaxError, u);
Py_DECREF(u);
return 0;
}
static void
ast_error_finish(const char *filename)
{
PyObject *type, *value, *tback, *errstr, *loc, *tmp;
long lineno;
assert(PyErr_Occurred());
if (!PyErr_ExceptionMatches(PyExc_SyntaxError))
return;
PyErr_Fetch(&type, &value, &tback);
errstr = PyTuple_GetItem(value, 0);
if (!errstr)
return;
Py_INCREF(errstr);
lineno = PyLong_AsLong(PyTuple_GetItem(value, 1));
if (lineno == -1) {
Py_DECREF(errstr);
return;
}
Py_DECREF(value);
loc = PyErr_ProgramText(filename, lineno);
if (!loc) {
Py_INCREF(Py_None);
loc = Py_None;
}
tmp = Py_BuildValue("(zlOO)", filename, lineno, Py_None, loc);
Py_DECREF(loc);
if (!tmp) {
Py_DECREF(errstr);
return;
}
value = PyTuple_Pack(2, errstr, tmp);
Py_DECREF(errstr);
Py_DECREF(tmp);
if (!value)
return;
PyErr_Restore(type, value, tback);
}
static int
ast_warn(struct compiling *c, const node *n, char *msg)
{
if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, LINENO(n),
NULL, NULL) < 0) {
/* if -Werr, change it to a SyntaxError */
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SyntaxWarning))
ast_error(n, msg);
return 0;
}
return 1;
}
static int
forbidden_check(struct compiling *c, const node *n, const char *x)
{
if (!strcmp(x, "None"))
return ast_error(n, "cannot assign to None");
if (!strcmp(x, "__debug__"))
return ast_error(n, "cannot assign to __debug__");
if (Py_Py3kWarningFlag) {
if (!(strcmp(x, "True") && strcmp(x, "False")) &&
!ast_warn(c, n, "assignment to True or False is forbidden in 3.x"))
return 0;
if (!strcmp(x, "nonlocal") &&
!ast_warn(c, n, "nonlocal is a keyword in 3.x"))
return 0;
}
return 1;
}
/* num_stmts() returns number of contained statements.
Use this routine to determine how big a sequence is needed for
the statements in a parse tree. Its raison d'etre is this bit of
grammar:
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
A simple_stmt can contain multiple small_stmt elements joined
by semicolons. If the arg is a simple_stmt, the number of
small_stmt elements is returned.
*/
static int
num_stmts(const node *n)
{
int i, l;
node *ch;
switch (TYPE(n)) {
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE)
return 0;
else
return num_stmts(CHILD(n, 0));
case file_input:
l = 0;
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == stmt)
l += num_stmts(ch);
}
return l;
case stmt:
return num_stmts(CHILD(n, 0));
case compound_stmt:
return 1;
case simple_stmt:
return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */
case suite:
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
if (NCH(n) == 1)
return num_stmts(CHILD(n, 0));
else {
i = 2;
l = 0;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++)
l += num_stmts(CHILD(n, i));
return l;
}
default: {
char buf[128];
sprintf(buf, "Non-statement found: %d %d",
TYPE(n), NCH(n));
Py_FatalError(buf);
}
}
assert(0);
return 0;
}
/* Transform the CST rooted at node * to the appropriate AST
*/
mod_ty
Ta27AST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename,
PyArena *arena)
{
int i, j, k, num;
asdl_seq *stmts = NULL;
asdl_seq *type_ignores = NULL;
stmt_ty s;
node *ch;
struct compiling c;
asdl_seq *argtypes = NULL;
expr_ty ret, arg;
if (flags && flags->cf_flags & PyCF_SOURCE_IS_UTF8) {
c.c_encoding = "utf-8";
if (TYPE(n) == encoding_decl) {
ast_error(n, "encoding declaration in Unicode string");
goto error;
}
} else if (TYPE(n) == encoding_decl) {
c.c_encoding = STR(n);
n = CHILD(n, 0);
} else {
c.c_encoding = NULL;
}
c.c_future_unicode = flags && flags->cf_flags & CO_FUTURE_UNICODE_LITERALS;
c.c_arena = arena;
c.c_filename = filename;
k = 0;
switch (TYPE(n)) {
case file_input:
stmts = asdl_seq_new(num_stmts(n), arena);
if (!stmts)
return NULL;
for (i = 0; i < NCH(n) - 1; i++) {
ch = CHILD(n, i);
if (TYPE(ch) == NEWLINE)
continue;
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
s = ast_for_stmt(&c, ch);
if (!s)
goto error;
asdl_seq_SET(stmts, k++, s);
}
else {
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < num; j++) {
s = ast_for_stmt(&c, CHILD(ch, j * 2));
if (!s)
goto error;
asdl_seq_SET(stmts, k++, s);
}
}
}
/* Type ignores are stored under the ENDMARKER in file_input. */
ch = CHILD(n, NCH(n) - 1);
REQ(ch, ENDMARKER);
num = NCH(ch);
type_ignores = _Py_asdl_seq_new(num, arena);
if (!type_ignores)
goto error;
for (i = 0; i < num; i++) {
type_ignore_ty ti = TypeIgnore(LINENO(CHILD(ch, i)), arena);
if (!ti)
goto error;
asdl_seq_SET(type_ignores, i, ti);
}
return Module(stmts, type_ignores, arena);
case eval_input: {
expr_ty testlist_ast;
/* XXX Why not comp_for here? */
testlist_ast = ast_for_testlist(&c, CHILD(n, 0));
if (!testlist_ast)
goto error;
return Expression(testlist_ast, arena);
}
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE) {
stmts = asdl_seq_new(1, arena);
if (!stmts)
goto error;
asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
arena));
if (!asdl_seq_GET(stmts, 0))
goto error;
return Interactive(stmts, arena);
}
else {
n = CHILD(n, 0);
num = num_stmts(n);
stmts = asdl_seq_new(num, arena);
if (!stmts)
goto error;
if (num == 1) {
s = ast_for_stmt(&c, n);
if (!s)
goto error;
asdl_seq_SET(stmts, 0, s);
}
else {
/* Only a simple_stmt can contain multiple statements. */
REQ(n, simple_stmt);
for (i = 0; i < NCH(n); i += 2) {
if (TYPE(CHILD(n, i)) == NEWLINE)
break;
s = ast_for_stmt(&c, CHILD(n, i));
if (!s)
goto error;
asdl_seq_SET(stmts, i / 2, s);
}
}
return Interactive(stmts, arena);
}
case func_type_input:
n = CHILD(n, 0);
REQ(n, func_type);
if (TYPE(CHILD(n, 1)) == typelist) {
ch = CHILD(n, 1);
/* this is overly permissive -- we don't pay any attention to
* stars on the args -- just parse them into an ordered list */
num = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test)
num++;
}
argtypes = _Py_asdl_seq_new(num, arena);
j = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test) {
arg = ast_for_expr(&c, CHILD(ch, i));
if (!arg)
goto error;
asdl_seq_SET(argtypes, j++, arg);
}
}
}
else
argtypes = _Py_asdl_seq_new(0, arena);
ret = ast_for_expr(&c, CHILD(n, NCH(n) - 1));
if (!ret)
goto error;
return FunctionType(argtypes, ret, arena);
default:
PyErr_Format(PyExc_SystemError,
"invalid node %d for Ta27AST_FromNode", TYPE(n));
goto error;
}
error:
ast_error_finish(filename);
return NULL;
}
/* Return the AST repr. of the operator represented as syntax (|, ^, etc.)
*/
static operator_ty
get_operator(const node *n)
{
switch (TYPE(n)) {
case VBAR:
return BitOr;
case CIRCUMFLEX:
return BitXor;
case AMPER:
return BitAnd;
case LEFTSHIFT:
return LShift;
case RIGHTSHIFT:
return RShift;
case PLUS:
return Add;
case MINUS:
return Sub;
case STAR:
return Mult;
case SLASH:
return Div;
case DOUBLESLASH:
return FloorDiv;
case PERCENT:
return Mod;
default:
return (operator_ty)0;
}
}
/* Set the context ctx for expr_ty e, recursively traversing e.
Only sets context for expr kinds that "can appear in assignment context"
(according to ../Parser/Python.asdl). For other expr kinds, it sets
an appropriate syntax error and returns false.
*/
static int
set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n)
{
asdl_seq *s = NULL;
/* If a particular expression type can't be used for assign / delete,
set expr_name to its name and an error message will be generated.
*/
const char* expr_name = NULL;
/* The ast defines augmented store and load contexts, but the
implementation here doesn't actually use them. The code may be
a little more complex than necessary as a result. It also means
that expressions in an augmented assignment have a Store context.
Consider restructuring so that augmented assignment uses
set_context(), too.
*/
assert(ctx != AugStore && ctx != AugLoad);
switch (e->kind) {
case Attribute_kind:
if (ctx == Store && !forbidden_check(c, n,
PyUnicode_AsUTF8(e->v.Attribute.attr)))
return 0;
e->v.Attribute.ctx = ctx;
break;
case Subscript_kind:
e->v.Subscript.ctx = ctx;
break;
case Name_kind:
if (ctx == Store && !forbidden_check(c, n,
PyUnicode_AsUTF8(e->v.Name.id)))
return 0;
e->v.Name.ctx = ctx;
break;
case List_kind:
e->v.List.ctx = ctx;
s = e->v.List.elts;
break;
case Tuple_kind:
if (asdl_seq_LEN(e->v.Tuple.elts)) {
e->v.Tuple.ctx = ctx;
s = e->v.Tuple.elts;
}
else {
expr_name = "()";
}
break;
case Lambda_kind:
expr_name = "lambda";
break;
case Call_kind:
expr_name = "function call";
break;
case BoolOp_kind:
case BinOp_kind:
case UnaryOp_kind:
expr_name = "operator";
break;
case GeneratorExp_kind:
expr_name = "generator expression";
break;
case Yield_kind:
expr_name = "yield expression";
break;
case ListComp_kind:
expr_name = "list comprehension";
break;
case SetComp_kind:
expr_name = "set comprehension";
break;
case DictComp_kind:
expr_name = "dict comprehension";
break;
case Dict_kind:
case Set_kind:
case Num_kind:
case Str_kind:
expr_name = "literal";
break;
case Compare_kind:
expr_name = "comparison";
break;
case Repr_kind:
expr_name = "repr";
break;
case IfExp_kind:
expr_name = "conditional expression";
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected expression in assignment %d (line %d)",
e->kind, e->lineno);
return 0;
}
/* Check for error string set by switch */
if (expr_name) {
char buf[300];
PyOS_snprintf(buf, sizeof(buf),
"can't %s %s",
ctx == Store ? "assign to" : "delete",
expr_name);
return ast_error(n, buf);
}
/* If the LHS is a list or tuple, we need to set the assignment
context for all the contained elements.
*/
if (s) {
int i;
for (i = 0; i < asdl_seq_LEN(s); i++) {
if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n))
return 0;
}
}
return 1;
}
static operator_ty
ast_for_augassign(struct compiling *c, const node *n)
{
REQ(n, augassign);
n = CHILD(n, 0);
switch (STR(n)[0]) {
case '+':
return Add;
case '-':
return Sub;
case '/':
if (STR(n)[1] == '/')
return FloorDiv;
else
return Div;
case '%':
return Mod;
case '<':
return LShift;
case '>':
return RShift;
case '&':
return BitAnd;
case '^':
return BitXor;
case '|':
return BitOr;
case '*':
if (STR(n)[1] == '*')
return Pow;
else
return Mult;
default:
PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n));
return (operator_ty)0;
}
}
static cmpop_ty
ast_for_comp_op(struct compiling *c, const node *n)
{
/* comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'
|'is' 'not'
*/
REQ(n, comp_op);
if (NCH(n) == 1) {
n = CHILD(n, 0);
switch (TYPE(n)) {
case LESS:
return Lt;
case GREATER:
return Gt;
case EQEQUAL: /* == */
return Eq;
case LESSEQUAL:
return LtE;
case GREATEREQUAL:
return GtE;
case NOTEQUAL:
return NotEq;
case NAME:
if (strcmp(STR(n), "in") == 0)
return In;
if (strcmp(STR(n), "is") == 0)
return Is;
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s",
STR(n));
return (cmpop_ty)0;
}
}
else if (NCH(n) == 2) {
/* handle "not in" and "is not" */
switch (TYPE(CHILD(n, 0))) {
case NAME:
if (strcmp(STR(CHILD(n, 1)), "in") == 0)
return NotIn;
if (strcmp(STR(CHILD(n, 0)), "is") == 0)
return IsNot;
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s",
STR(CHILD(n, 0)), STR(CHILD(n, 1)));
return (cmpop_ty)0;
}
}
PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children",
NCH(n));
return (cmpop_ty)0;
}
static asdl_seq *
seq_for_testlist(struct compiling *c, const node *n)
{
/* testlist: test (',' test)* [','] */
asdl_seq *seq;
expr_ty expression;
int i;
assert(TYPE(n) == testlist ||
TYPE(n) == listmaker ||
TYPE(n) == testlist_comp ||
TYPE(n) == testlist_safe ||
TYPE(n) == testlist1);
seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
assert(TYPE(CHILD(n, i)) == test || TYPE(CHILD(n, i)) == old_test);
expression = ast_for_expr(c, CHILD(n, i));
if (!expression)
return NULL;
assert(i / 2 < seq->size);
asdl_seq_SET(seq, i / 2, expression);
}
return seq;
}
static expr_ty
compiler_complex_args(struct compiling *c, const node *n)
{
int i, len = (NCH(n) + 1) / 2;
expr_ty result;
asdl_seq *args = asdl_seq_new(len, c->c_arena);
if (!args)
return NULL;
/* fpdef: NAME | '(' fplist ')'
fplist: fpdef (',' fpdef)* [',']
*/
REQ(n, fplist);
for (i = 0; i < len; i++) {
PyObject *arg_id;
const node *fpdef_node = CHILD(n, 2*i);
const node *child;
expr_ty arg;
set_name:
/* fpdef_node is either a NAME or an fplist */
child = CHILD(fpdef_node, 0);
if (TYPE(child) == NAME) {
if (!forbidden_check(c, n, STR(child)))
return NULL;
arg_id = NEW_IDENTIFIER(child);
if (!arg_id)
return NULL;
arg = Name(arg_id, Store, LINENO(child), child->n_col_offset,
c->c_arena);
}
else {
assert(TYPE(fpdef_node) == fpdef);
/* fpdef_node[0] is not a name, so it must be '(', get CHILD[1] */
child = CHILD(fpdef_node, 1);
assert(TYPE(child) == fplist);
/* NCH == 1 means we have (x), we need to elide the extra parens */
if (NCH(child) == 1) {
fpdef_node = CHILD(child, 0);
assert(TYPE(fpdef_node) == fpdef);
goto set_name;
}
arg = compiler_complex_args(c, child);
}
asdl_seq_SET(args, i, arg);
}
result = Tuple(args, Store, LINENO(n), n->n_col_offset, c->c_arena);
if (!set_context(c, result, Store, n))
return NULL;
return result;
}
/* Create AST for argument list. */
static arguments_ty
ast_for_arguments(struct compiling *c, const node *n)
{
/* parameters: '(' [varargslist] ')'
varargslist: ((fpdef ['=' test] ',' [TYPE_COMMENT])*
('*' NAME [',' [TYPE_COMMENT] '**' NAME] [TYPE_COMMENT] | '**' NAME [TYPE_COMMENT]) |
fpdef ['=' test] (',' [TYPE_COMMENT] fpdef ['=' test])* [','] [TYPE_COMMENT])
*/
int i, j, k, l, n_args = 0, n_all_args = 0, n_defaults = 0, found_default = 0;
asdl_seq *args, *defaults, *type_comments = NULL;
identifier vararg = NULL, kwarg = NULL;
node *ch;
if (TYPE(n) == parameters) {
if (NCH(n) == 2) /* () as argument list */
return arguments(NULL, NULL, NULL, NULL, NULL, c->c_arena);
n = CHILD(n, 1);
}
REQ(n, varargslist);
/* first count the number of normal args & defaults */
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == fpdef)
n_args++;
if (TYPE(ch) == EQUAL)
n_defaults++;
if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
n_all_args++;
}
n_all_args += n_args;
args = (n_args ? asdl_seq_new(n_args, c->c_arena) : NULL);
if (!args && n_args)
return NULL;
defaults = (n_defaults ? asdl_seq_new(n_defaults, c->c_arena) : NULL);
if (!defaults && n_defaults)
return NULL;
/* type_comments will be lazily initialized if needed. If there are no
per-argument type comments, it will remain NULL. Otherwise, it will be
an asdl_seq with length equal to the number of args (including varargs
and kwargs, if present) and with members set to the string of each arg's
type comment, if present, or NULL otherwise.
*/
/* fpdef: NAME | '(' fplist ')'
fplist: fpdef (',' fpdef)* [',']
*/
i = 0;
j = 0; /* index for defaults */
k = 0; /* index for args */
l = 0; /* index for type comments */
while (i < NCH(n)) {
ch = CHILD(n, i);
switch (TYPE(ch)) {
case fpdef: {
int complex_args = 0, parenthesized = 0;
handle_fpdef:
/* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is
anything other than EQUAL or a comma? */
/* XXX Should NCH(n) check be made a separate check? */
if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
expr_ty expression = ast_for_expr(c, CHILD(n, i + 2));
if (!expression)
return NULL;
assert(defaults != NULL);
asdl_seq_SET(defaults, j++, expression);
i += 2;
found_default = 1;
}
else if (found_default) {
/* def f((x)=4): pass should raise an error.
def f((x, (y))): pass will just incur the tuple unpacking warning. */
if (parenthesized && !complex_args) {
ast_error(n, "parenthesized arg with default");
return NULL;
}
ast_error(n,
"non-default argument follows default argument");
return NULL;
}
if (NCH(ch) == 3) {
ch = CHILD(ch, 1);
/* def foo((x)): is not complex, special case. */
if (NCH(ch) != 1) {
/* We have complex arguments, setup for unpacking. */
if (Py_Py3kWarningFlag && !ast_warn(c, ch,
"tuple parameter unpacking has been removed in 3.x"))
return NULL;
complex_args = 1;
asdl_seq_SET(args, k++, compiler_complex_args(c, ch));
if (!asdl_seq_GET(args, k-1))
return NULL;
} else {
/* def foo((x)): setup for checking NAME below. */
/* Loop because there can be many parens and tuple
unpacking mixed in. */
parenthesized = 1;
ch = CHILD(ch, 0);
assert(TYPE(ch) == fpdef);
goto handle_fpdef;
}
}
if (TYPE(CHILD(ch, 0)) == NAME) {
PyObject *id;
expr_ty name;
if (!forbidden_check(c, n, STR(CHILD(ch, 0))))
return NULL;
id = NEW_IDENTIFIER(CHILD(ch, 0));
if (!id)
return NULL;
name = Name(id, Param, LINENO(ch), ch->n_col_offset,
c->c_arena);
if (!name)
return NULL;
asdl_seq_SET(args, k++, name);
}
i += 1; /* the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
if (parenthesized && Py_Py3kWarningFlag &&
!ast_warn(c, ch, "parenthesized argument names "
"are invalid in 3.x"))
return NULL;
break;
}
case STAR:
if (!forbidden_check(c, CHILD(n, i+1), STR(CHILD(n, i+1))))
return NULL;
vararg = NEW_IDENTIFIER(CHILD(n, i+1));
if (!vararg)
return NULL;
i += 2; /* the star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case DOUBLESTAR:
if (!forbidden_check(c, CHILD(n, i+1), STR(CHILD(n, i+1))))
return NULL;
kwarg = NEW_IDENTIFIER(CHILD(n, i+1));
if (!kwarg)
return NULL;
i += 2; /* the double star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case TYPE_COMMENT:
assert(l < k + !!vararg + !!kwarg);
if (!type_comments) {
/* lazily allocate the type_comments seq for perf reasons */
type_comments = asdl_seq_new(n_all_args, c->c_arena);
if (!type_comments)
return NULL;
}
while (l < k + !!vararg + !!kwarg - 1) {
asdl_seq_SET(type_comments, l++, NULL);
}
asdl_seq_SET(type_comments, l++, NEW_TYPE_COMMENT(ch));
i += 1;
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected node in varargslist: %d @ %d",
TYPE(ch), i);
return NULL;
}
}
if (type_comments) {
while (l < n_all_args) {
asdl_seq_SET(type_comments, l++, NULL);
}
}
return arguments(args, vararg, kwarg, defaults, type_comments, c->c_arena);
}
static expr_ty
ast_for_dotted_name(struct compiling *c, const node *n)
{
expr_ty e;
identifier id;
int lineno, col_offset;
int i;
REQ(n, dotted_name);
lineno = LINENO(n);
col_offset = n->n_col_offset;
id = NEW_IDENTIFIER(CHILD(n, 0));
if (!id)
return NULL;
e = Name(id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
for (i = 2; i < NCH(n); i+=2) {
id = NEW_IDENTIFIER(CHILD(n, i));
if (!id)
return NULL;
e = Attribute(e, id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
}
return e;
}
static expr_ty
ast_for_decorator(struct compiling *c, const node *n)
{
/* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */
expr_ty d = NULL;
expr_ty name_expr;
REQ(n, decorator);
REQ(CHILD(n, 0), AT);
REQ(RCHILD(n, -1), NEWLINE);
name_expr = ast_for_dotted_name(c, CHILD(n, 1));
if (!name_expr)
return NULL;
if (NCH(n) == 3) { /* No arguments */
d = name_expr;
name_expr = NULL;
}
else if (NCH(n) == 5) { /* Call with no arguments */
d = Call(name_expr, NULL, NULL, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
if (!d)
return NULL;
name_expr = NULL;
}
else {
d = ast_for_call(c, CHILD(n, 3), name_expr);
if (!d)
return NULL;
name_expr = NULL;
}
return d;
}
static asdl_seq*
ast_for_decorators(struct compiling *c, const node *n)
{
asdl_seq* decorator_seq;
expr_ty d;
int i;
REQ(n, decorators);
decorator_seq = asdl_seq_new(NCH(n), c->c_arena);
if (!decorator_seq)
return NULL;
for (i = 0; i < NCH(n); i++) {
d = ast_for_decorator(c, CHILD(n, i));
if (!d)
return NULL;
asdl_seq_SET(decorator_seq, i, d);
}
return decorator_seq;
}
static stmt_ty
ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* funcdef: 'def' NAME parameters ':' [TYPE_COMMENT] suite */
identifier name;
arguments_ty args;
asdl_seq *body;
int name_i = 1;
node *tc;
string type_comment = NULL;
REQ(n, funcdef);
name = NEW_IDENTIFIER(CHILD(n, name_i));
if (!name)
return NULL;
else if (!forbidden_check(c, CHILD(n, name_i), STR(CHILD(n, name_i))))
return NULL;
args = ast_for_arguments(c, CHILD(n, name_i + 1));
if (!args)
return NULL;
if (TYPE(CHILD(n, name_i + 3)) == TYPE_COMMENT) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, name_i + 3));
name_i += 1;
}
body = ast_for_suite(c, CHILD(n, name_i + 3));
if (!body)
return NULL;
if (!type_comment && NCH(CHILD(n, name_i + 3)) > 1) {
/* If the function doesn't have a type comment on the same line, check
* if the suite has a type comment in it. */
tc = CHILD(CHILD(n, name_i + 3), 1);
if (TYPE(tc) == TYPE_COMMENT)
type_comment = NEW_TYPE_COMMENT(tc);
}
return FunctionDef(name, args, body, decorator_seq, type_comment, LINENO(n),
n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_decorated(struct compiling *c, const node *n)
{
/* decorated: decorators (classdef | funcdef) */
stmt_ty thing = NULL;
asdl_seq *decorator_seq = NULL;
REQ(n, decorated);
decorator_seq = ast_for_decorators(c, CHILD(n, 0));
if (!decorator_seq)
return NULL;
assert(TYPE(CHILD(n, 1)) == funcdef ||
TYPE(CHILD(n, 1)) == classdef);
if (TYPE(CHILD(n, 1)) == funcdef) {
thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == classdef) {
thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
}
/* we count the decorators in when talking about the class' or
function's line number */
if (thing) {
thing->lineno = LINENO(n);
thing->col_offset = n->n_col_offset;
}
return thing;
}
static expr_ty
ast_for_lambdef(struct compiling *c, const node *n)
{
/* lambdef: 'lambda' [varargslist] ':' test */
arguments_ty args;
expr_ty expression;
if (NCH(n) == 3) {
args = arguments(NULL, NULL, NULL, NULL, NULL, c->c_arena);
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
}
else {
args = ast_for_arguments(c, CHILD(n, 1));
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 3));
if (!expression)
return NULL;
}
return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_ifexpr(struct compiling *c, const node *n)
{
/* test: or_test 'if' or_test 'else' test */
expr_ty expression, body, orelse;
assert(NCH(n) == 5);
body = ast_for_expr(c, CHILD(n, 0));
if (!body)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
orelse = ast_for_expr(c, CHILD(n, 4));
if (!orelse)
return NULL;
return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset,
c->c_arena);
}
/* XXX(nnorwitz): the listcomp and genexpr code should be refactored
so there is only a single version. Possibly for loops can also re-use
the code.
*/
/* Count the number of 'for' loop in a list comprehension.
Helper for ast_for_listcomp().
*/
static int
count_list_fors(struct compiling *c, const node *n)
{
int n_fors = 0;
node *ch = CHILD(n, 1);
count_list_for:
n_fors++;
REQ(ch, list_for);
if (NCH(ch) == 5)
ch = CHILD(ch, 4);
else
return n_fors;
count_list_iter:
REQ(ch, list_iter);
ch = CHILD(ch, 0);
if (TYPE(ch) == list_for)
goto count_list_for;
else if (TYPE(ch) == list_if) {
if (NCH(ch) == 3) {
ch = CHILD(ch, 2);
goto count_list_iter;
}
else
return n_fors;
}
/* Should never be reached */
PyErr_SetString(PyExc_SystemError, "logic error in count_list_fors");
return -1;
}
/* Count the number of 'if' statements in a list comprehension.
Helper for ast_for_listcomp().
*/
static int
count_list_ifs(struct compiling *c, const node *n)
{
int n_ifs = 0;
count_list_iter:
REQ(n, list_iter);
if (TYPE(CHILD(n, 0)) == list_for)
return n_ifs;
n = CHILD(n, 0);
REQ(n, list_if);
n_ifs++;
if (NCH(n) == 2)
return n_ifs;
n = CHILD(n, 2);
goto count_list_iter;
}
static expr_ty
ast_for_listcomp(struct compiling *c, const node *n)
{
/* listmaker: test ( list_for | (',' test)* [','] )
list_for: 'for' exprlist 'in' testlist_safe [list_iter]
list_iter: list_for | list_if
list_if: 'if' test [list_iter]
testlist_safe: test [(',' test)+ [',']]
*/
expr_ty elt, first;
asdl_seq *listcomps;
int i, n_fors;
node *ch;
REQ(n, listmaker);
assert(NCH(n) > 1);
elt = ast_for_expr(c, CHILD(n, 0));
if (!elt)
return NULL;
n_fors = count_list_fors(c, n);
if (n_fors == -1)
return NULL;
listcomps = asdl_seq_new(n_fors, c->c_arena);
if (!listcomps)
return NULL;
ch = CHILD(n, 1);
for (i = 0; i < n_fors; i++) {
comprehension_ty lc;
asdl_seq *t;
expr_ty expression;
node *for_ch;
REQ(ch, list_for);
for_ch = CHILD(ch, 1);
t = ast_for_exprlist(c, for_ch, Store);
if (!t)
return NULL;
expression = ast_for_testlist(c, CHILD(ch, 3));
if (!expression)
return NULL;
/* Check the # of children rather than the length of t, since
[x for x, in ... ] has 1 element in t, but still requires a Tuple.
*/
first = (expr_ty)asdl_seq_GET(t, 0);
if (NCH(for_ch) == 1)
lc = comprehension(first, expression, NULL, c->c_arena);
else
lc = comprehension(Tuple(t, Store, first->lineno, first->col_offset,
c->c_arena),
expression, NULL, c->c_arena);
if (!lc)
return NULL;
if (NCH(ch) == 5) {
int j, n_ifs;
asdl_seq *ifs;
expr_ty list_for_expr;
ch = CHILD(ch, 4);
n_ifs = count_list_ifs(c, ch);
if (n_ifs == -1)
return NULL;
ifs = asdl_seq_new(n_ifs, c->c_arena);
if (!ifs)
return NULL;
for (j = 0; j < n_ifs; j++) {
REQ(ch, list_iter);
ch = CHILD(ch, 0);
REQ(ch, list_if);
list_for_expr = ast_for_expr(c, CHILD(ch, 1));
if (!list_for_expr)
return NULL;
asdl_seq_SET(ifs, j, list_for_expr);
if (NCH(ch) == 3)
ch = CHILD(ch, 2);
}
/* on exit, must guarantee that ch is a list_for */
if (TYPE(ch) == list_iter)
ch = CHILD(ch, 0);
lc->ifs = ifs;
}
asdl_seq_SET(listcomps, i, lc);
}
return ListComp(elt, listcomps, LINENO(n), n->n_col_offset, c->c_arena);
}
/*
Count the number of 'for' loops in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_fors(struct compiling *c, const node *n)
{
int n_fors = 0;
count_comp_for:
n_fors++;
REQ(n, comp_for);
if (NCH(n) == 5)
n = CHILD(n, 4);
else
return n_fors;
count_comp_iter:
REQ(n, comp_iter);
n = CHILD(n, 0);
if (TYPE(n) == comp_for)
goto count_comp_for;
else if (TYPE(n) == comp_if) {
if (NCH(n) == 3) {
n = CHILD(n, 2);
goto count_comp_iter;
}
else
return n_fors;
}
/* Should never be reached */
PyErr_SetString(PyExc_SystemError,
"logic error in count_comp_fors");
return -1;
}
/* Count the number of 'if' statements in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_ifs(struct compiling *c, const node *n)
{
int n_ifs = 0;
while (1) {
REQ(n, comp_iter);
if (TYPE(CHILD(n, 0)) == comp_for)
return n_ifs;
n = CHILD(n, 0);
REQ(n, comp_if);
n_ifs++;
if (NCH(n) == 2)
return n_ifs;
n = CHILD(n, 2);
}
}
static asdl_seq *
ast_for_comprehension(struct compiling *c, const node *n)
{
int i, n_fors;
asdl_seq *comps;
n_fors = count_comp_fors(c, n);
if (n_fors == -1)
return NULL;
comps = asdl_seq_new(n_fors, c->c_arena);
if (!comps)
return NULL;
for (i = 0; i < n_fors; i++) {
comprehension_ty comp;
asdl_seq *t;
expr_ty expression, first;
node *for_ch;
REQ(n, comp_for);
for_ch = CHILD(n, 1);
t = ast_for_exprlist(c, for_ch, Store);
if (!t)
return NULL;
expression = ast_for_expr(c, CHILD(n, 3));
if (!expression)
return NULL;
/* Check the # of children rather than the length of t, since
(x for x, in ...) has 1 element in t, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(t, 0);
if (NCH(for_ch) == 1)
comp = comprehension(first, expression, NULL, c->c_arena);
else
comp = comprehension(Tuple(t, Store, first->lineno, first->col_offset,
c->c_arena),
expression, NULL, c->c_arena);
if (!comp)
return NULL;
if (NCH(n) == 5) {
int j, n_ifs;
asdl_seq *ifs;
n = CHILD(n, 4);
n_ifs = count_comp_ifs(c, n);
if (n_ifs == -1)
return NULL;
ifs = asdl_seq_new(n_ifs, c->c_arena);
if (!ifs)
return NULL;
for (j = 0; j < n_ifs; j++) {
REQ(n, comp_iter);
n = CHILD(n, 0);
REQ(n, comp_if);
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
asdl_seq_SET(ifs, j, expression);
if (NCH(n) == 3)
n = CHILD(n, 2);
}
/* on exit, must guarantee that n is a comp_for */
if (TYPE(n) == comp_iter)
n = CHILD(n, 0);
comp->ifs = ifs;
}
asdl_seq_SET(comps, i, comp);
}
return comps;
}
static expr_ty
ast_for_itercomp(struct compiling *c, const node *n, int type)
{
expr_ty elt;
asdl_seq *comps;
assert(NCH(n) > 1);
elt = ast_for_expr(c, CHILD(n, 0));
if (!elt)
return NULL;
comps = ast_for_comprehension(c, CHILD(n, 1));
if (!comps)
return NULL;
if (type == COMP_GENEXP)
return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else if (type == COMP_SETCOMP)
return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else
/* Should never happen */
return NULL;
}
static expr_ty
ast_for_dictcomp(struct compiling *c, const node *n)
{
expr_ty key, value;
asdl_seq *comps;
assert(NCH(n) > 3);
REQ(CHILD(n, 1), COLON);
key = ast_for_expr(c, CHILD(n, 0));
if (!key)
return NULL;
value = ast_for_expr(c, CHILD(n, 2));
if (!value)
return NULL;
comps = ast_for_comprehension(c, CHILD(n, 3));
if (!comps)
return NULL;
return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_genexp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument));
return ast_for_itercomp(c, n, COMP_GENEXP);
}
static expr_ty
ast_for_setcomp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (dictorsetmaker));
return ast_for_itercomp(c, n, COMP_SETCOMP);
}
static expr_ty
ast_for_atom(struct compiling *c, const node *n)
{
/* atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']'
| '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
*/
node *ch = CHILD(n, 0);
switch (TYPE(ch)) {
case NAME: {
/* All names start in Load context, but may later be
changed. */
PyObject *name = NEW_IDENTIFIER(ch);
if (!name)
return NULL;
return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
case STRING: {
PyObject *kind, *str = parsestrplus(c, n);
const char *raw, *s = STR(CHILD(n, 0));
/* currently Python allows up to 2 string modifiers */
char *ch, s_kind[3] = {0, 0, 0};
ch = s_kind;
raw = s;
while (*raw && *raw != '\'' && *raw != '"') {
*ch++ = *raw++;
}
kind = PyUnicode_FromString(s_kind);
if (!kind) {
return NULL;
}
if (!str) {
#ifdef Py_USING_UNICODE
if (PyErr_ExceptionMatches(PyExc_UnicodeError)){
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr) {
const char *s = "";
char buf[128];
s = _PyUnicode_AsString(errstr);
PyOS_snprintf(buf, sizeof(buf), "(unicode error) %s", s);
ast_error(n, buf);
Py_DECREF(errstr);
} else {
ast_error(n, "(unicode error) unknown error");
}
Py_DECREF(type);
Py_DECREF(value);
Py_XDECREF(tback);
}
#endif
return NULL;
}
PyArena_AddPyObject(c->c_arena, str);
return Str(str, kind, LINENO(n), n->n_col_offset, c->c_arena);
}
case NUMBER: {
PyObject *pynum = parsenumber(c, STR(ch));
if (!pynum)
return NULL;
PyArena_AddPyObject(c->c_arena, pynum);
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
case LPAR: /* some parenthesized expressions */
ch = CHILD(n, 1);
if (TYPE(ch) == RPAR)
return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (TYPE(ch) == yield_expr)
return ast_for_expr(c, ch);
return ast_for_testlist_comp(c, ch);
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
REQ(ch, listmaker);
if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
asdl_seq *elts = seq_for_testlist(c, ch);
if (!elts)
return NULL;
return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
else
return ast_for_listcomp(c, ch);
case LBRACE: {
/* dictorsetmaker:
* (test ':' test (comp_for | (',' test ':' test)* [','])) |
* (test (comp_for | (',' test)* [',']))
*/
int i, size;
asdl_seq *keys, *values;
ch = CHILD(n, 1);
if (TYPE(ch) == RBRACE) {
/* it's an empty dict */
return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
} else if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
/* it's a simple set */
asdl_seq *elts;
size = (NCH(ch) + 1) / 2; /* +1 in case no trailing comma */
elts = asdl_seq_new(size, c->c_arena);
if (!elts)
return NULL;
for (i = 0; i < NCH(ch); i += 2) {
expr_ty expression;
expression = ast_for_expr(c, CHILD(ch, i));
if (!expression)
return NULL;
asdl_seq_SET(elts, i / 2, expression);
}
return Set(elts, LINENO(n), n->n_col_offset, c->c_arena);
} else if (TYPE(CHILD(ch, 1)) == comp_for) {
/* it's a set comprehension */
return ast_for_setcomp(c, ch);
} else if (NCH(ch) > 3 && TYPE(CHILD(ch, 3)) == comp_for) {
return ast_for_dictcomp(c, ch);
} else {
/* it's a dict */
size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */
keys = asdl_seq_new(size, c->c_arena);
if (!keys)
return NULL;
values = asdl_seq_new(size, c->c_arena);
if (!values)
return NULL;
for (i = 0; i < NCH(ch); i += 4) {
expr_ty expression;
expression = ast_for_expr(c, CHILD(ch, i));
if (!expression)
return NULL;
asdl_seq_SET(keys, i / 4, expression);
expression = ast_for_expr(c, CHILD(ch, i + 2));
if (!expression)
return NULL;
asdl_seq_SET(values, i / 4, expression);
}
return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena);
}
}
case BACKQUOTE: { /* repr */
expr_ty expression;
if (Py_Py3kWarningFlag &&
!ast_warn(c, n, "backquote not supported in 3.x; use repr()"))
return NULL;
expression = ast_for_testlist(c, CHILD(n, 1));
if (!expression)
return NULL;
return Repr(expression, LINENO(n), n->n_col_offset, c->c_arena);
}
default:
PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
return NULL;
}
}
static slice_ty
ast_for_slice(struct compiling *c, const node *n)
{
node *ch;
expr_ty lower = NULL, upper = NULL, step = NULL;
REQ(n, subscript);
/*
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
*/
ch = CHILD(n, 0);
if (TYPE(ch) == DOT)
return Ellipsis(c->c_arena);
if (NCH(n) == 1 && TYPE(ch) == test) {
/* 'step' variable hold no significance in terms of being used over
other vars */
step = ast_for_expr(c, ch);
if (!step)
return NULL;
return Index(step, c->c_arena);
}
if (TYPE(ch) == test) {
lower = ast_for_expr(c, ch);
if (!lower)
return NULL;
}
/* If there's an upper bound it's in the second or third position. */
if (TYPE(ch) == COLON) {
if (NCH(n) > 1) {
node *n2 = CHILD(n, 1);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
} else if (NCH(n) > 2) {
node *n2 = CHILD(n, 2);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
ch = CHILD(n, NCH(n) - 1);
if (TYPE(ch) == sliceop) {
if (NCH(ch) == 1) {
/*
This is an extended slice (ie "x[::]") with no expression in the
step field. We set this literally to "None" in order to
disambiguate it from x[:]. (The interpreter might have to call
__getslice__ for x[:], but it must call __getitem__ for x[::].)
*/
identifier none = new_identifier("None", c->c_arena);
if (!none)
return NULL;
ch = CHILD(ch, 0);
step = Name(none, Load, LINENO(ch), ch->n_col_offset, c->c_arena);
if (!step)
return NULL;
} else {
ch = CHILD(ch, 1);
if (TYPE(ch) == test) {
step = ast_for_expr(c, ch);
if (!step)
return NULL;
}
}
}
return Slice(lower, upper, step, c->c_arena);
}
static expr_ty
ast_for_binop(struct compiling *c, const node *n)
{
/* Must account for a sequence of expressions.
How should A op B op C by represented?
BinOp(BinOp(A, op, B), op, C).
*/
int i, nops;
expr_ty expr1, expr2, result;
operator_ty newoperator;
expr1 = ast_for_expr(c, CHILD(n, 0));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 2));
if (!expr2)
return NULL;
newoperator = get_operator(CHILD(n, 1));
if (!newoperator)
return NULL;
result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
c->c_arena);
if (!result)
return NULL;
nops = (NCH(n) - 1) / 2;
for (i = 1; i < nops; i++) {
expr_ty tmp_result, tmp;
const node* next_oper = CHILD(n, i * 2 + 1);
newoperator = get_operator(next_oper);
if (!newoperator)
return NULL;
tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
if (!tmp)
return NULL;
tmp_result = BinOp(result, newoperator, tmp,
LINENO(next_oper), next_oper->n_col_offset,
c->c_arena);
if (!tmp_result)
return NULL;
result = tmp_result;
}
return result;
}
static expr_ty
ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr)
{
/* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
*/
REQ(n, trailer);
if (TYPE(CHILD(n, 0)) == LPAR) {
if (NCH(n) == 2)
return Call(left_expr, NULL, NULL, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
else
return ast_for_call(c, CHILD(n, 1), left_expr);
}
else if (TYPE(CHILD(n, 0)) == DOT ) {
PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1));
if (!attr_id)
return NULL;
return Attribute(left_expr, attr_id, Load,
LINENO(n), n->n_col_offset, c->c_arena);
}
else {
REQ(CHILD(n, 0), LSQB);
REQ(CHILD(n, 2), RSQB);
n = CHILD(n, 1);
if (NCH(n) == 1) {
slice_ty slc = ast_for_slice(c, CHILD(n, 0));
if (!slc)
return NULL;
return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset,
c->c_arena);
}
else {
/* The grammar is ambiguous here. The ambiguity is resolved
by treating the sequence as a tuple literal if there are
no slice features.
*/
int j;
slice_ty slc;
expr_ty e;
bool simple = true;
asdl_seq *slices, *elts;
slices = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!slices)
return NULL;
for (j = 0; j < NCH(n); j += 2) {
slc = ast_for_slice(c, CHILD(n, j));
if (!slc)
return NULL;
if (slc->kind != Index_kind)
simple = false;
asdl_seq_SET(slices, j / 2, slc);
}
if (!simple) {
return Subscript(left_expr, ExtSlice(slices, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
/* extract Index values and put them in a Tuple */
elts = asdl_seq_new(asdl_seq_LEN(slices), c->c_arena);
if (!elts)
return NULL;
for (j = 0; j < asdl_seq_LEN(slices); ++j) {
slc = (slice_ty)asdl_seq_GET(slices, j);
assert(slc->kind == Index_kind && slc->v.Index.value);
asdl_seq_SET(elts, j, slc->v.Index.value);
}
e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (!e)
return NULL;
return Subscript(left_expr, Index(e, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
}
static expr_ty
ast_for_factor(struct compiling *c, const node *n)
{
node *pfactor, *ppower, *patom, *pnum;
expr_ty expression;
/* If the unary - operator is applied to a constant, don't generate
a UNARY_NEGATIVE opcode. Just store the approriate value as a
constant. The peephole optimizer already does something like
this but it doesn't handle the case where the constant is
(sys.maxint - 1). In that case, we want a PyIntObject, not a
PyLongObject.
*/
if (TYPE(CHILD(n, 0)) == MINUS &&
NCH(n) == 2 &&
TYPE((pfactor = CHILD(n, 1))) == factor &&
NCH(pfactor) == 1 &&
TYPE((ppower = CHILD(pfactor, 0))) == power &&
NCH(ppower) == 1 &&
TYPE((patom = CHILD(ppower, 0))) == atom &&
TYPE((pnum = CHILD(patom, 0))) == NUMBER) {
PyObject *pynum;
char *s = PyObject_MALLOC(strlen(STR(pnum)) + 2);
if (s == NULL)
return NULL;
s[0] = '-';
strcpy(s + 1, STR(pnum));
pynum = parsenumber(c, s);
PyObject_FREE(s);
if (!pynum)
return NULL;
PyArena_AddPyObject(c->c_arena, pynum);
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
switch (TYPE(CHILD(n, 0))) {
case PLUS:
return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case MINUS:
return UnaryOp(USub, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case TILDE:
return UnaryOp(Invert, expression, LINENO(n),
n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError, "unhandled factor: %d",
TYPE(CHILD(n, 0)));
return NULL;
}
static expr_ty
ast_for_power(struct compiling *c, const node *n)
{
/* power: atom trailer* ('**' factor)*
*/
int i;
expr_ty e, tmp;
REQ(n, power);
e = ast_for_atom(c, CHILD(n, 0));
if (!e)
return NULL;
if (NCH(n) == 1)
return e;
for (i = 1; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) != trailer)
break;
tmp = ast_for_trailer(c, ch, e);
if (!tmp)
return NULL;
tmp->lineno = e->lineno;
tmp->col_offset = e->col_offset;
e = tmp;
}
if (TYPE(CHILD(n, NCH(n) - 1)) == factor) {
expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1));
if (!f)
return NULL;
tmp = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena);
if (!tmp)
return NULL;
e = tmp;
}
return e;
}
/* Do not name a variable 'expr'! Will cause a compile error.
*/
static expr_ty
ast_for_expr(struct compiling *c, const node *n)
{
/* handle the full range of simple expressions
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom trailer* ('**' factor)*
As well as modified versions that exist for backward compatibility,
to explicitly allow:
[ x for x in lambda: 0, lambda: 1 ]
(which would be ambiguous without these extra rules)
old_test: or_test | old_lambdef
old_lambdef: 'lambda' [vararglist] ':' old_test
*/
asdl_seq *seq;
int i;
loop:
switch (TYPE(n)) {
case test:
case old_test:
if (TYPE(CHILD(n, 0)) == lambdef ||
TYPE(CHILD(n, 0)) == old_lambdef)
return ast_for_lambdef(c, CHILD(n, 0));
else if (NCH(n) > 1)
return ast_for_ifexpr(c, n);
/* Fallthrough */
case or_test:
case and_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
expr_ty e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
}
if (!strcmp(STR(CHILD(n, 1)), "and"))
return BoolOp(And, seq, LINENO(n), n->n_col_offset,
c->c_arena);
assert(!strcmp(STR(CHILD(n, 1)), "or"));
return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena);
case not_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return UnaryOp(Not, expression, LINENO(n), n->n_col_offset,
c->c_arena);
}
case comparison:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression;
asdl_int_seq *ops;
asdl_seq *cmps;
ops = asdl_int_seq_new(NCH(n) / 2, c->c_arena);
if (!ops)
return NULL;
cmps = asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!cmps) {
return NULL;
}
for (i = 1; i < NCH(n); i += 2) {
cmpop_ty newoperator;
newoperator = ast_for_comp_op(c, CHILD(n, i));
if (!newoperator) {
return NULL;
}
expression = ast_for_expr(c, CHILD(n, i + 1));
if (!expression) {
return NULL;
}
asdl_seq_SET(ops, i / 2, newoperator);
asdl_seq_SET(cmps, i / 2, expression);
}
expression = ast_for_expr(c, CHILD(n, 0));
if (!expression) {
return NULL;
}
return Compare(expression, ops, cmps, LINENO(n),
n->n_col_offset, c->c_arena);
}
break;
/* The next five cases all handle BinOps. The main body of code
is the same in each case, but the switch turned inside out to
reuse the code for each type of operator.
*/
case expr:
case xor_expr:
case and_expr:
case shift_expr:
case arith_expr:
case term:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_binop(c, n);
case yield_expr: {
expr_ty exp = NULL;
if (NCH(n) == 2) {
exp = ast_for_testlist(c, CHILD(n, 1));
if (!exp)
return NULL;
}
return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case factor:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_factor(c, n);
case power:
return ast_for_power(c, n);
default:
PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n));
return NULL;
}
/* should never get here unless if error is set */
return NULL;
}
static expr_ty
ast_for_call(struct compiling *c, const node *n, expr_ty func)
{
/*
arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
| '**' test)
argument: [test '='] test [comp_for] # Really [keyword '='] test
*/
int i, nargs, nkeywords, ngens;
asdl_seq *args;
asdl_seq *keywords;
expr_ty vararg = NULL, kwarg = NULL;
REQ(n, arglist);
nargs = 0;
nkeywords = 0;
ngens = 0;
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
if (NCH(ch) == 1)
nargs++;
else if (TYPE(CHILD(ch, 1)) == comp_for)
ngens++;
else
nkeywords++;
}
}
if (ngens > 1 || (ngens && (nargs || nkeywords))) {
ast_error(n, "Generator expression must be parenthesized "
"if not sole argument");
return NULL;
}
if (nargs + nkeywords + ngens > 255) {
ast_error(n, "more than 255 arguments");
return NULL;
}
args = asdl_seq_new(nargs + ngens, c->c_arena);
if (!args)
return NULL;
keywords = asdl_seq_new(nkeywords, c->c_arena);
if (!keywords)
return NULL;
nargs = 0;
nkeywords = 0;
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
expr_ty e;
if (NCH(ch) == 1) {
if (nkeywords) {
ast_error(CHILD(ch, 0),
"non-keyword arg after keyword arg");
return NULL;
}
if (vararg) {
ast_error(CHILD(ch, 0),
"only named arguments may follow *expression");
return NULL;
}
e = ast_for_expr(c, CHILD(ch, 0));
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else if (TYPE(CHILD(ch, 1)) == comp_for) {
e = ast_for_genexp(c, ch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else {
keyword_ty kw;
identifier key;
int k;
const char *tmp;
/* CHILD(ch, 0) is test, but must be an identifier? */
e = ast_for_expr(c, CHILD(ch, 0));
if (!e)
return NULL;
/* f(lambda x: x[0] = 3) ends up getting parsed with
* LHS test = lambda x: x[0], and RHS test = 3.
* SF bug 132313 points out that complaining about a keyword
* then is very confusing.
*/
if (e->kind == Lambda_kind) {
ast_error(CHILD(ch, 0),
"lambda cannot contain assignment");
return NULL;
} else if (e->kind != Name_kind) {
ast_error(CHILD(ch, 0), "keyword can't be an expression");
return NULL;
}
key = e->v.Name.id;
if (!forbidden_check(c, CHILD(ch, 0), PyUnicode_AsUTF8(key)))
return NULL;
for (k = 0; k < nkeywords; k++) {
tmp = _PyUnicode_AsString(
((keyword_ty)asdl_seq_GET(keywords, k))->arg);
if (!strcmp(tmp, _PyUnicode_AsString(key))) {
ast_error(CHILD(ch, 0), "keyword argument repeated");
return NULL;
}
}
e = ast_for_expr(c, CHILD(ch, 2));
if (!e)
return NULL;
kw = keyword(key, e, c->c_arena);
if (!kw)
return NULL;
asdl_seq_SET(keywords, nkeywords++, kw);
}
}
else if (TYPE(ch) == STAR) {
vararg = ast_for_expr(c, CHILD(n, i+1));
if (!vararg)
return NULL;
i++;
}
else if (TYPE(ch) == DOUBLESTAR) {
kwarg = ast_for_expr(c, CHILD(n, i+1));
if (!kwarg)
return NULL;
i++;
}
}
return Call(func, args, keywords, vararg, kwarg, func->lineno,
func->col_offset, c->c_arena);
}
static expr_ty
ast_for_testlist(struct compiling *c, const node* n)
{
/* testlist_comp: test (',' test)* [','] */
/* testlist: test (',' test)* [','] */
/* testlist_safe: test (',' test)+ [','] */
/* testlist1: test (',' test)* */
assert(NCH(n) > 0);
if (TYPE(n) == testlist_comp) {
if (NCH(n) > 1)
assert(TYPE(CHILD(n, 1)) != comp_for);
}
else {
assert(TYPE(n) == testlist ||
TYPE(n) == testlist_safe ||
TYPE(n) == testlist1);
}
if (NCH(n) == 1)
return ast_for_expr(c, CHILD(n, 0));
else {
asdl_seq *tmp = seq_for_testlist(c, n);
if (!tmp)
return NULL;
return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
static expr_ty
ast_for_testlist_comp(struct compiling *c, const node* n)
{
/* testlist_comp: test ( comp_for | (',' test)* [','] ) */
/* argument: test [ comp_for ] */
assert(TYPE(n) == testlist_comp || TYPE(n) == argument);
if (NCH(n) > 1 && TYPE(CHILD(n, 1)) == comp_for)
return ast_for_genexp(c, n);
return ast_for_testlist(c, n);
}
/* like ast_for_testlist() but returns a sequence */
static asdl_seq*
ast_for_class_bases(struct compiling *c, const node* n)
{
/* testlist: test (',' test)* [','] */
assert(NCH(n) > 0);
REQ(n, testlist);
if (NCH(n) == 1) {
expr_ty base;
asdl_seq *bases = asdl_seq_new(1, c->c_arena);
if (!bases)
return NULL;
base = ast_for_expr(c, CHILD(n, 0));
if (!base)
return NULL;
asdl_seq_SET(bases, 0, base);
return bases;
}
return seq_for_testlist(c, n);
}
static stmt_ty
ast_for_expr_stmt(struct compiling *c, const node *n)
{
int num;
REQ(n, expr_stmt);
/* expr_stmt: testlist (augassign (yield_expr|testlist)
| ('=' (yield_expr|testlist))* [TYPE_COMMENT])
testlist: test (',' test)* [',']
augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^='
| '<<=' | '>>=' | '**=' | '//='
test: ... here starts the operator precendence dance
*/
num = NCH(n);
if (num == 1 || (num == 2 && TYPE(CHILD(n, 1)) == TYPE_COMMENT)) {
expr_ty e = ast_for_testlist(c, CHILD(n, 0));
if (!e)
return NULL;
return Expr(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (TYPE(CHILD(n, 1)) == augassign) {
expr_ty expr1, expr2;
operator_ty newoperator;
node *ch = CHILD(n, 0);
expr1 = ast_for_testlist(c, ch);
if (!expr1)
return NULL;
if(!set_context(c, expr1, Store, ch))
return NULL;
/* set_context checks that most expressions are not the left side.
Augmented assignments can only have a name, a subscript, or an
attribute on the left, though, so we have to explicitly check for
those. */
switch (expr1->kind) {
case Name_kind:
case Attribute_kind:
case Subscript_kind:
break;
default:
ast_error(ch, "illegal expression for augmented assignment");
return NULL;
}
ch = CHILD(n, 2);
if (TYPE(ch) == testlist)
expr2 = ast_for_testlist(c, ch);
else
expr2 = ast_for_expr(c, ch);
if (!expr2)
return NULL;
newoperator = ast_for_augassign(c, CHILD(n, 1));
if (!newoperator)
return NULL;
return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
c->c_arena);
}
else {
int i, nch_minus_type, has_type_comment;
asdl_seq *targets;
node *value;
expr_ty expression;
string type_comment;
/* a normal assignment */
REQ(CHILD(n, 1), EQUAL);
has_type_comment = TYPE(CHILD(n, num - 1)) == TYPE_COMMENT;
nch_minus_type = num - has_type_comment;
targets = asdl_seq_new(nch_minus_type / 2, c->c_arena);
if (!targets)
return NULL;
for (i = 0; i < nch_minus_type - 2; i += 2) {
expr_ty e;
node *ch = CHILD(n, i);
if (TYPE(ch) == yield_expr) {
ast_error(ch, "assignment to yield expression not possible");
return NULL;
}
e = ast_for_testlist(c, ch);
if (!e)
return NULL;
/* set context to assign */
if (!set_context(c, e, Store, CHILD(n, i)))
return NULL;
asdl_seq_SET(targets, i / 2, e);
}
value = CHILD(n, nch_minus_type - 1);
if (TYPE(value) == testlist)
expression = ast_for_testlist(c, value);
else
expression = ast_for_expr(c, value);
if (!expression)
return NULL;
if (has_type_comment)
type_comment = NEW_TYPE_COMMENT(CHILD(n, nch_minus_type));
else
type_comment = NULL;
return Assign(targets, expression, type_comment, LINENO(n), n->n_col_offset,
c->c_arena);
}
}
static stmt_ty
ast_for_print_stmt(struct compiling *c, const node *n)
{
/* print_stmt: 'print' ( [ test (',' test)* [','] ]
| '>>' test [ (',' test)+ [','] ] )
*/
expr_ty dest = NULL, expression;
asdl_seq *seq = NULL;
bool nl;
int i, j, values_count, start = 1;
REQ(n, print_stmt);
if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) {
dest = ast_for_expr(c, CHILD(n, 2));
if (!dest)
return NULL;
start = 4;
}
values_count = (NCH(n) + 1 - start) / 2;
if (values_count) {
seq = asdl_seq_new(values_count, c->c_arena);
if (!seq)
return NULL;
for (i = start, j = 0; i < NCH(n); i += 2, ++j) {
expression = ast_for_expr(c, CHILD(n, i));
if (!expression)
return NULL;
asdl_seq_SET(seq, j, expression);
}
}
nl = (TYPE(CHILD(n, NCH(n) - 1)) == COMMA) ? false : true;
return Print(dest, seq, nl, LINENO(n), n->n_col_offset, c->c_arena);
}
static asdl_seq *
ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context)
{
asdl_seq *seq;
int i;
expr_ty e;
REQ(n, exprlist);
seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
if (context && !set_context(c, e, context, CHILD(n, i)))
return NULL;
}
return seq;
}
static stmt_ty
ast_for_del_stmt(struct compiling *c, const node *n)
{
asdl_seq *expr_list;
/* del_stmt: 'del' exprlist */
REQ(n, del_stmt);
expr_list = ast_for_exprlist(c, CHILD(n, 1), Del);
if (!expr_list)
return NULL;
return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_flow_stmt(struct compiling *c, const node *n)
{
/*
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
| yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
yield_expr: 'yield' testlist
raise_stmt: 'raise' [test [',' test [',' test]]]
*/
node *ch;
REQ(n, flow_stmt);
ch = CHILD(n, 0);
switch (TYPE(ch)) {
case break_stmt:
return Break(LINENO(n), n->n_col_offset, c->c_arena);
case continue_stmt:
return Continue(LINENO(n), n->n_col_offset, c->c_arena);
case yield_stmt: { /* will reduce to yield_expr */
expr_ty exp = ast_for_expr(c, CHILD(ch, 0));
if (!exp)
return NULL;
return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case return_stmt:
if (NCH(ch) == 1)
return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena);
else {
expr_ty expression = ast_for_testlist(c, CHILD(ch, 1));
if (!expression)
return NULL;
return Return(expression, LINENO(n), n->n_col_offset,
c->c_arena);
}
case raise_stmt:
if (NCH(ch) == 1)
return Raise(NULL, NULL, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
else if (NCH(ch) == 2) {
expr_ty expression = ast_for_expr(c, CHILD(ch, 1));
if (!expression)
return NULL;
return Raise(expression, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
}
else if (NCH(ch) == 4) {
expr_ty expr1, expr2;
expr1 = ast_for_expr(c, CHILD(ch, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(ch, 3));
if (!expr2)
return NULL;
return Raise(expr1, expr2, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (NCH(ch) == 6) {
expr_ty expr1, expr2, expr3;
expr1 = ast_for_expr(c, CHILD(ch, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(ch, 3));
if (!expr2)
return NULL;
expr3 = ast_for_expr(c, CHILD(ch, 5));
if (!expr3)
return NULL;
return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset,
c->c_arena);
}
default:
PyErr_Format(PyExc_SystemError,
"unexpected flow_stmt: %d", TYPE(ch));
return NULL;
}
}
static alias_ty
alias_for_import_name(struct compiling *c, const node *n, int store)
{
/*
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
dotted_name: NAME ('.' NAME)*
*/
PyObject *str, *name;
loop:
switch (TYPE(n)) {
case import_as_name: {
node *name_node = CHILD(n, 0);
str = NULL;
if (NCH(n) == 3) {
node *str_node = CHILD(n, 2);
if (store && !forbidden_check(c, str_node, STR(str_node)))
return NULL;
str = NEW_IDENTIFIER(str_node);
if (!str)
return NULL;
}
else {
if (!forbidden_check(c, name_node, STR(name_node)))
return NULL;
}
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
return alias(name, str, c->c_arena);
}
case dotted_as_name:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
node *asname_node = CHILD(n, 2);
alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0);
if (!a)
return NULL;
assert(!a->asname);
if (!forbidden_check(c, asname_node, STR(asname_node)))
return NULL;
a->asname = NEW_IDENTIFIER(asname_node);
if (!a->asname)
return NULL;
return a;
}
break;
case dotted_name:
if (NCH(n) == 1) {
node *name_node = CHILD(n, 0);
if (store && !forbidden_check(c, name_node, STR(name_node)))
return NULL;
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
return alias(name, NULL, c->c_arena);
}
else {
/* Create a string of the form "a.b.c" */
int i;
size_t len;
char *s;
PyObject *uni;
len = 0;
for (i = 0; i < NCH(n); i += 2)
/* length of string plus one for the dot */
len += strlen(STR(CHILD(n, i))) + 1;
len--; /* the last name doesn't have a dot */
str = PyBytes_FromStringAndSize(NULL, len);
if (!str)
return NULL;
s = PyBytes_AS_STRING(str);
if (!s)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
char *sch = STR(CHILD(n, i));
strcpy(s, STR(CHILD(n, i)));
s += strlen(sch);
*s++ = '.';
}
--s;
*s = '\0';
uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str),
PyBytes_GET_SIZE(str),
NULL);
Py_DECREF(str);
if (!uni)
return NULL;
str = uni;
PyUnicode_InternInPlace(&str);
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
}
break;
case STAR:
str = PyUnicode_InternFromString("*");
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
default:
PyErr_Format(PyExc_SystemError,
"unexpected import name: %d", TYPE(n));
return NULL;
}
PyErr_SetString(PyExc_SystemError, "unhandled import name condition");
return NULL;
}
static stmt_ty
ast_for_import_stmt(struct compiling *c, const node *n)
{
/*
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
import_from: 'from' ('.'* dotted_name | '.') 'import'
('*' | '(' import_as_names ')' | import_as_names)
*/
int lineno;
int col_offset;
int i;
asdl_seq *aliases;
REQ(n, import_stmt);
lineno = LINENO(n);
col_offset = n->n_col_offset;
n = CHILD(n, 0);
if (TYPE(n) == import_name) {
n = CHILD(n, 1);
REQ(n, dotted_as_names);
aliases = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
return Import(aliases, lineno, col_offset, c->c_arena);
}
else if (TYPE(n) == import_from) {
int n_children;
int idx, ndots = 0;
alias_ty mod = NULL;
identifier modname = NULL;
/* Count the number of dots (for relative imports) and check for the
optional module name */
for (idx = 1; idx < NCH(n); idx++) {
if (TYPE(CHILD(n, idx)) == dotted_name) {
mod = alias_for_import_name(c, CHILD(n, idx), 0);
if (!mod)
return NULL;
idx++;
break;
} else if (TYPE(CHILD(n, idx)) != DOT) {
break;
}
ndots++;
}
idx++; /* skip over the 'import' keyword */
switch (TYPE(CHILD(n, idx))) {
case STAR:
/* from ... import * */
n = CHILD(n, idx);
n_children = 1;
break;
case LPAR:
/* from ... import (x, y, z) */
n = CHILD(n, idx + 1);
n_children = NCH(n);
break;
case import_as_names:
/* from ... import x, y, z */
n = CHILD(n, idx);
n_children = NCH(n);
if (n_children % 2 == 0) {
ast_error(n, "trailing comma not allowed without"
" surrounding parentheses");
return NULL;
}
break;
default:
ast_error(n, "Unexpected node-type in from-import");
return NULL;
}
aliases = asdl_seq_new((n_children + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
/* handle "from ... import *" special b/c there's no children */
if (TYPE(n) == STAR) {
alias_ty import_alias = alias_for_import_name(c, n, 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, 0, import_alias);
}
else {
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
}
if (mod != NULL)
modname = mod->name;
return ImportFrom(modname, aliases, ndots, lineno, col_offset,
c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unknown import statement: starts with command '%s'",
STR(CHILD(n, 0)));
return NULL;
}
static stmt_ty
ast_for_global_stmt(struct compiling *c, const node *n)
{
/* global_stmt: 'global' NAME (',' NAME)* */
identifier name;
asdl_seq *s;
int i;
REQ(n, global_stmt);
s = asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!s)
return NULL;
for (i = 1; i < NCH(n); i += 2) {
name = NEW_IDENTIFIER(CHILD(n, i));
if (!name)
return NULL;
asdl_seq_SET(s, i / 2, name);
}
return Global(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_exec_stmt(struct compiling *c, const node *n)
{
expr_ty expr1, globals = NULL, locals = NULL;
int n_children = NCH(n);
if (n_children != 2 && n_children != 4 && n_children != 6) {
PyErr_Format(PyExc_SystemError,
"poorly formed 'exec' statement: %d parts to statement",
n_children);
return NULL;
}
/* exec_stmt: 'exec' expr ['in' test [',' test]] */
REQ(n, exec_stmt);
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
if (expr1->kind == Tuple_kind && n_children < 4 &&
(asdl_seq_LEN(expr1->v.Tuple.elts) == 2 ||
asdl_seq_LEN(expr1->v.Tuple.elts) == 3)) {
/* Backwards compatibility: passing exec args as a tuple */
globals = asdl_seq_GET(expr1->v.Tuple.elts, 1);
if (asdl_seq_LEN(expr1->v.Tuple.elts) == 3) {
locals = asdl_seq_GET(expr1->v.Tuple.elts, 2);
}
expr1 = asdl_seq_GET(expr1->v.Tuple.elts, 0);
}
if (n_children >= 4) {
globals = ast_for_expr(c, CHILD(n, 3));
if (!globals)
return NULL;
}
if (n_children == 6) {
locals = ast_for_expr(c, CHILD(n, 5));
if (!locals)
return NULL;
}
return Exec(expr1, globals, locals, LINENO(n), n->n_col_offset,
c->c_arena);
}
static stmt_ty
ast_for_assert_stmt(struct compiling *c, const node *n)
{
/* assert_stmt: 'assert' test [',' test] */
REQ(n, assert_stmt);
if (NCH(n) == 2) {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return Assert(expression, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (NCH(n) == 4) {
expr_ty expr1, expr2;
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 3));
if (!expr2)
return NULL;
return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"improper number of parts to 'assert' statement: %d",
NCH(n));
return NULL;
}
static asdl_seq *
ast_for_suite(struct compiling *c, const node *n)
{
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
asdl_seq *seq;
stmt_ty s;
int i, total, num, end, pos = 0;
node *ch;
REQ(n, suite);
total = num_stmts(n);
seq = asdl_seq_new(total, c->c_arena);
if (!seq)
return NULL;
if (TYPE(CHILD(n, 0)) == simple_stmt) {
n = CHILD(n, 0);
/* simple_stmt always ends with a NEWLINE,
and may have a trailing SEMI
*/
end = NCH(n) - 1;
if (TYPE(CHILD(n, end - 1)) == SEMI)
end--;
/* loop by 2 to skip semi-colons */
for (i = 0; i < end; i += 2) {
ch = CHILD(n, i);
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
else {
i = 2;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++) {
ch = CHILD(n, i);
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
/* small_stmt or compound_stmt with only one child */
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
else {
int j;
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < NCH(ch); j += 2) {
/* statement terminates with a semi-colon ';' */
if (NCH(CHILD(ch, j)) == 0) {
assert((j + 1) == NCH(ch));
break;
}
s = ast_for_stmt(c, CHILD(ch, j));
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
}
}
assert(pos == seq->size);
return seq;
}
static stmt_ty
ast_for_if_stmt(struct compiling *c, const node *n)
{
/* if_stmt: 'if' test ':' suite ('elif' test ':' suite)*
['else' ':' suite]
*/
char *s;
REQ(n, if_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
s = STR(CHILD(n, 4));
/* s[2], the third character in the string, will be
's' for el_s_e, or
'i' for el_i_f
*/
if (s[2] == 's') {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (s[2] == 'i') {
int i, n_elif, has_else = 0;
expr_ty expression;
asdl_seq *suite_seq;
asdl_seq *orelse = NULL;
n_elif = NCH(n) - 4;
/* must reference the child n_elif+1 since 'else' token is third,
not fourth, child from the end. */
if (TYPE(CHILD(n, (n_elif + 1))) == NAME
&& STR(CHILD(n, (n_elif + 1)))[2] == 's') {
has_else = 1;
n_elif -= 3;
}
n_elif /= 4;
if (has_else) {
asdl_seq *suite_seq2;
orelse = asdl_seq_new(1, c->c_arena);
if (!orelse)
return NULL;
expression = ast_for_expr(c, CHILD(n, NCH(n) - 6));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4));
if (!suite_seq)
return NULL;
suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!suite_seq2)
return NULL;
asdl_seq_SET(orelse, 0,
If(expression, suite_seq, suite_seq2,
LINENO(CHILD(n, NCH(n) - 6)),
CHILD(n, NCH(n) - 6)->n_col_offset,
c->c_arena));
/* the just-created orelse handled the last elif */
n_elif--;
}
for (i = 0; i < n_elif; i++) {
int off = 5 + (n_elif - i - 1) * 4;
asdl_seq *newobj = asdl_seq_new(1, c->c_arena);
if (!newobj)
return NULL;
expression = ast_for_expr(c, CHILD(n, off));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, off + 2));
if (!suite_seq)
return NULL;
asdl_seq_SET(newobj, 0,
If(expression, suite_seq, orelse,
LINENO(CHILD(n, off)),
CHILD(n, off)->n_col_offset, c->c_arena));
orelse = newobj;
}
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, orelse,
LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unexpected token in 'if' statement: %s", s);
return NULL;
}
static stmt_ty
ast_for_while_stmt(struct compiling *c, const node *n)
{
/* while_stmt: 'while' test ':' suite ['else' ':' suite] */
REQ(n, while_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (NCH(n) == 7) {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return While(expression, seq1, seq2, LINENO(n), n->n_col_offset,
c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of tokens for 'while' statement: %d",
NCH(n));
return NULL;
}
static stmt_ty
ast_for_for_stmt(struct compiling *c, const node *n)
{
asdl_seq *_target, *seq = NULL, *suite_seq;
expr_ty expression;
expr_ty target, first;
const node *node_target;
int has_type_comment;
string type_comment;
/* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */
REQ(n, for_stmt);
has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT;
if (NCH(n) == 9 + has_type_comment) {
seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment));
if (!seq)
return NULL;
}
node_target = CHILD(n, 1);
_target = ast_for_exprlist(c, node_target, Store);
if (!_target)
return NULL;
/* Check the # of children rather than the length of _target, since
for x, in ... has 1 element in _target, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(_target, 0);
if (NCH(node_target) == 1)
target = first;
else
target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);
expression = ast_for_testlist(c, CHILD(n, 3));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment));
if (!suite_seq)
return NULL;
if (has_type_comment)
type_comment = NEW_TYPE_COMMENT(CHILD(n, 5));
else
type_comment = NULL;
return For(target, expression, suite_seq, seq, type_comment, LINENO(n), n->n_col_offset,
c->c_arena);
}
static excepthandler_ty
ast_for_except_clause(struct compiling *c, const node *exc, node *body)
{
/* except_clause: 'except' [test [(',' | 'as') test]] */
REQ(exc, except_clause);
REQ(body, suite);
if (NCH(exc) == 1) {
asdl_seq *suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 2) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 4) {
asdl_seq *suite_seq;
expr_ty expression;
expr_ty e = ast_for_expr(c, CHILD(exc, 3));
if (!e)
return NULL;
if (!set_context(c, e, Store, CHILD(exc, 3)))
return NULL;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, e, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of children for 'except' clause: %d",
NCH(exc));
return NULL;
}
static stmt_ty
ast_for_try_stmt(struct compiling *c, const node *n)
{
const int nch = NCH(n);
int n_except = (nch - 3)/3;
asdl_seq *body, *orelse = NULL, *finally = NULL;
REQ(n, try_stmt);
body = ast_for_suite(c, CHILD(n, 2));
if (body == NULL)
return NULL;
if (TYPE(CHILD(n, nch - 3)) == NAME) {
if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) {
if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) {
/* we can assume it's an "else",
because nch >= 9 for try-else-finally and
it would otherwise have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 4));
if (orelse == NULL)
return NULL;
n_except--;
}
finally = ast_for_suite(c, CHILD(n, nch - 1));
if (finally == NULL)
return NULL;
n_except--;
}
else {
/* we can assume it's an "else",
otherwise it would have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 1));
if (orelse == NULL)
return NULL;
n_except--;
}
}
else if (TYPE(CHILD(n, nch - 3)) != except_clause) {
ast_error(n, "malformed 'try' statement");
return NULL;
}
if (n_except > 0) {
int i;
stmt_ty except_st;
/* process except statements to create a try ... except */
asdl_seq *handlers = asdl_seq_new(n_except, c->c_arena);
if (handlers == NULL)
return NULL;
for (i = 0; i < n_except; i++) {
excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3),
CHILD(n, 5 + i * 3));
if (!e)
return NULL;
asdl_seq_SET(handlers, i, e);
}
except_st = TryExcept(body, handlers, orelse, LINENO(n),
n->n_col_offset, c->c_arena);
if (!finally)
return except_st;
/* if a 'finally' is present too, we nest the TryExcept within a
TryFinally to emulate try ... except ... finally */
body = asdl_seq_new(1, c->c_arena);
if (body == NULL)
return NULL;
asdl_seq_SET(body, 0, except_st);
}
/* must be a try ... finally (except clauses are in body, if any exist) */
assert(finally != NULL);
return TryFinally(body, finally, LINENO(n), n->n_col_offset, c->c_arena);
}
/* with_item: test ['as' expr] */
static stmt_ty
ast_for_with_item(struct compiling *c, const node *n, asdl_seq *content, string type_comment)
{
expr_ty context_expr, optional_vars = NULL;
REQ(n, with_item);
context_expr = ast_for_expr(c, CHILD(n, 0));
if (!context_expr)
return NULL;
if (NCH(n) == 3) {
optional_vars = ast_for_expr(c, CHILD(n, 2));
if (!optional_vars) {
return NULL;
}
if (!set_context(c, optional_vars, Store, n)) {
return NULL;
}
}
return With(context_expr, optional_vars, content, type_comment, LINENO(n),
n->n_col_offset, c->c_arena);
}
/* with_stmt: 'with' with_item (',' with_item)* ':' [TYPE_COMMENT] suite */
static stmt_ty
ast_for_with_stmt(struct compiling *c, const node *n)
{
int i, has_type_comment;
stmt_ty ret;
asdl_seq *inner;
string type_comment;
REQ(n, with_stmt);
has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT;
/* process the with items inside-out */
i = NCH(n) - 1;
/* the suite of the innermost with item is the suite of the with stmt */
inner = ast_for_suite(c, CHILD(n, i));
if (!inner)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2));
i--;
} else
type_comment = NULL;
for (;;) {
i -= 2;
ret = ast_for_with_item(c, CHILD(n, i), inner, type_comment);
if (!ret)
return NULL;
/* was this the last item? */
if (i == 1)
break;
/* if not, wrap the result so far in a new sequence */
inner = asdl_seq_new(1, c->c_arena);
if (!inner)
return NULL;
asdl_seq_SET(inner, 0, ret);
}
return ret;
}
static stmt_ty
ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
PyObject *classname;
asdl_seq *bases, *s;
REQ(n, classdef);
if (!forbidden_check(c, n, STR(CHILD(n, 1))))
return NULL;
if (NCH(n) == 4) {
s = ast_for_suite(c, CHILD(n, 3));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
return ClassDef(classname, NULL, s, decorator_seq, LINENO(n),
n->n_col_offset, c->c_arena);
}
/* check for empty base list */
if (TYPE(CHILD(n,3)) == RPAR) {
s = ast_for_suite(c, CHILD(n,5));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
return ClassDef(classname, NULL, s, decorator_seq, LINENO(n),
n->n_col_offset, c->c_arena);
}
/* else handle the base class list */
bases = ast_for_class_bases(c, CHILD(n, 3));
if (!bases)
return NULL;
s = ast_for_suite(c, CHILD(n, 6));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
return ClassDef(classname, bases, s, decorator_seq,
LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_stmt(struct compiling *c, const node *n)
{
if (TYPE(n) == stmt) {
assert(NCH(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == simple_stmt) {
assert(num_stmts(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == small_stmt) {
n = CHILD(n, 0);
/* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt
| flow_stmt | import_stmt | global_stmt | exec_stmt
| assert_stmt
*/
switch (TYPE(n)) {
case expr_stmt:
return ast_for_expr_stmt(c, n);
case print_stmt:
return ast_for_print_stmt(c, n);
case del_stmt:
return ast_for_del_stmt(c, n);
case pass_stmt:
return Pass(LINENO(n), n->n_col_offset, c->c_arena);
case flow_stmt:
return ast_for_flow_stmt(c, n);
case import_stmt:
return ast_for_import_stmt(c, n);
case global_stmt:
return ast_for_global_stmt(c, n);
case exec_stmt:
return ast_for_exec_stmt(c, n);
case assert_stmt:
return ast_for_assert_stmt(c, n);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
else {
/* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
| funcdef | classdef | decorated
*/
node *ch = CHILD(n, 0);
REQ(n, compound_stmt);
switch (TYPE(ch)) {
case if_stmt:
return ast_for_if_stmt(c, ch);
case while_stmt:
return ast_for_while_stmt(c, ch);
case for_stmt:
return ast_for_for_stmt(c, ch);
case try_stmt:
return ast_for_try_stmt(c, ch);
case with_stmt:
return ast_for_with_stmt(c, ch);
case funcdef:
return ast_for_funcdef(c, ch, NULL);
case classdef:
return ast_for_classdef(c, ch, NULL);
case decorated:
return ast_for_decorated(c, ch);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
}
static PyObject *
parsenumber(struct compiling *c, const char *s)
{
const char *end;
long x;
double dx;
int old_style_octal;
#ifndef WITHOUT_COMPLEX
Py_complex complex;
int imflag;
#endif
assert(s != NULL);
errno = 0;
end = s + strlen(s) - 1;
#ifndef WITHOUT_COMPLEX
imflag = *end == 'j' || *end == 'J';
#endif
if (*end == 'l' || *end == 'L') {
/* Make a copy without the trailing 'L' */
size_t len = end - s + 1;
char *copy = malloc(len);
PyObject *result;
if (copy == NULL)
return PyErr_NoMemory();
memcpy(copy, s, len);
copy[len - 1] = '\0';
old_style_octal = len > 2 && copy[0] == '0' && copy[1] >= '0' && copy[1] <= '9';
result = PyLong_FromString(copy, (char **)0, old_style_octal ? 8 : 0);
free(copy);
return result;
}
x = Ta27OS_strtol((char *)s, (char **)&end, 0);
if (*end == '\0') {
if (errno != 0) {
old_style_octal = end - s > 1 && s[0] == '0' && s[1] >= '0' && s[1] <= '9';
return PyLong_FromString((char *)s, (char **)0, old_style_octal ? 8 : 0);
}
return PyLong_FromLong(x);
}
/* XXX Huge floats may silently fail */
#ifndef WITHOUT_COMPLEX
if (imflag) {
complex.real = 0.;
complex.imag = PyOS_string_to_double(s, (char **)&end, NULL);
if (complex.imag == -1.0 && PyErr_Occurred())
return NULL;
return PyComplex_FromCComplex(complex);
}
else
#endif
{
dx = PyOS_string_to_double(s, NULL, NULL);
if (dx == -1.0 && PyErr_Occurred())
return NULL;
return PyFloat_FromDouble(dx);
}
}
/* adapted from Python 3.5.1 */
static PyObject *
decode_utf8(struct compiling *c, const char **sPtr, const char *end)
{
#ifndef Py_USING_UNICODE
Py_FatalError("decode_utf8 should not be called in this build.");
return NULL;
#else
const char *s, *t;
t = s = *sPtr;
/* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
while (s < end && (*s & 0x80)) s++;
*sPtr = s;
return PyUnicode_DecodeUTF8(t, s - t, NULL);
#endif
}
#ifdef Py_USING_UNICODE
/* taken from Python 3.5.1 */
static PyObject *
decode_unicode(struct compiling *c, const char *s, size_t len, int rawmode, const char *encoding)
{
PyObject *v, *u;
char *buf;
char *p;
const char *end;
if (encoding == NULL) {
u = NULL;
} else {
/* check for integer overflow */
if (len > PY_SIZE_MAX / 6)
return NULL;
/* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
"\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
u = PyBytes_FromStringAndSize((char *)NULL, len * 6);
if (u == NULL)
return NULL;
p = buf = PyBytes_AsString(u);
end = s + len;
while (s < end) {
if (*s == '\\') {
*p++ = *s++;
if (*s & 0x80) {
strcpy(p, "u005c");
p += 5;
}
}
if (*s & 0x80) { /* XXX inefficient */
PyObject *w;
int kind;
void *data;
Py_ssize_t len, i;
w = decode_utf8(c, &s, end);
if (w == NULL) {
Py_DECREF(u);
return NULL;
}
kind = PyUnicode_KIND(w);
data = PyUnicode_DATA(w);
len = PyUnicode_GET_LENGTH(w);
for (i = 0; i < len; i++) {
Py_UCS4 chr = PyUnicode_READ(kind, data, i);
sprintf(p, "\\U%08x", chr);
p += 10;
}
/* Should be impossible to overflow */
assert(p - buf <= Py_SIZE(u));
Py_DECREF(w);
} else {
*p++ = *s++;
}
}
len = p - buf;
s = buf;
}
if (rawmode)
v = PyUnicode_DecodeRawUnicodeEscape(s, len, NULL);
else
v = PyUnicode_DecodeUnicodeEscape(s, len, NULL);
Py_XDECREF(u);
return v;
}
#endif
/* s is a Python string literal, including the bracketing quote characters,
* and r &/or u prefixes (if any), and embedded escape sequences (if any).
* parsestr parses it, and returns the decoded Python string object.
*/
static PyObject *
parsestr(struct compiling *c, const node *n, const char *s)
{
size_t len, i;
int quote = Py_CHARMASK(*s);
int rawmode = 0;
int need_encoding;
int unicode = c->c_future_unicode;
int bytes = 0;
if (isalpha(quote) || quote == '_') {
if (quote == 'u' || quote == 'U') {
quote = *++s;
unicode = 1;
}
if (quote == 'b' || quote == 'B') {
quote = *++s;
unicode = 0;
bytes = 1;
}
if (quote == 'r' || quote == 'R') {
quote = *++s;
rawmode = 1;
}
}
if (quote != '\'' && quote != '\"') {
PyErr_BadInternalCall();
return NULL;
}
s++;
len = strlen(s);
if (len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string to parse is too long");
return NULL;
}
if (s[--len] != quote) {
PyErr_BadInternalCall();
return NULL;
}
if (len >= 4 && s[0] == quote && s[1] == quote) {
s += 2;
len -= 2;
if (s[--len] != quote || s[--len] != quote) {
PyErr_BadInternalCall();
return NULL;
}
}
if (Py_Py3kWarningFlag && bytes) {
for (i = 0; i < len; i++) {
if ((unsigned char)s[i] > 127) {
if (!ast_warn(c, n,
"non-ascii bytes literals not supported in 3.x"))
return NULL;
break;
}
}
}
#ifdef Py_USING_UNICODE
if (unicode || Py_UnicodeFlag) {
return decode_unicode(c, s, len, rawmode, c->c_encoding);
}
#endif
need_encoding = (c->c_encoding != NULL &&
strcmp(c->c_encoding, "utf-8") != 0 &&
strcmp(c->c_encoding, "iso-8859-1") != 0);
if (rawmode || strchr(s, '\\') == NULL) {
if (need_encoding) {
#ifndef Py_USING_UNICODE
/* This should not happen - we never see any other
encoding. */
Py_FatalError(
"cannot deal with encodings in this build.");
#else
PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL);
if (u == NULL)
return NULL;
v = PyUnicode_AsEncodedString(u, c->c_encoding, NULL);
Py_DECREF(u);
return v;
#endif
} else {
return PyBytes_FromStringAndSize(s, len);
}
}
return PyBytes_DecodeEscape(s, len, NULL, 1,
need_encoding ? c->c_encoding : NULL);
}
/* Build a Python string object out of a STRING atom. This takes care of
* compile-time literal catenation, calling parsestr() on each piece, and
* pasting the intermediate results together.
*/
static PyObject *
parsestrplus(struct compiling *c, const node *n)
{
PyObject *v;
int i;
REQ(CHILD(n, 0), STRING);
if ((v = parsestr(c, n, STR(CHILD(n, 0)))) != NULL) {
/* String literal concatenation */
for (i = 1; i < NCH(n); i++) {
PyObject *s;
s = parsestr(c, n, STR(CHILD(n, i)));
if (s == NULL)
goto onError;
if (PyBytes_Check(v) && PyBytes_Check(s)) {
PyBytes_ConcatAndDel(&v, s);
if (v == NULL)
goto onError;
}
#ifdef Py_USING_UNICODE
else {
PyObject *temp;
/* Python 2's PyUnicode_FromObject (which is
* called on the arguments to PyUnicode_Concat)
* automatically converts Bytes objects into
* Str objects, but in Python 3 it throws a
* syntax error. To allow mixed literal
* concatenation e.g. "foo" u"bar" (which is
* valid in Python 2), we have to explicitly
* check for Bytes and convert manually. */
if (PyBytes_Check(s)) {
temp = PyUnicode_FromEncodedObject(s, NULL, "strict");
Py_DECREF(s);
s = temp;
}
if (PyBytes_Check(v)) {
temp = PyUnicode_FromEncodedObject(v, NULL, "strict");
Py_DECREF(v);
v = temp;
}
temp = PyUnicode_Concat(v, s);
Py_DECREF(s);
Py_DECREF(v);
v = temp;
if (v == NULL)
goto onError;
}
#endif
}
}
return v;
onError:
Py_XDECREF(v);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1282_1 |
crossvul-cpp_data_bad_922_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD %
% T H H R R E SS H H O O L D D %
% T HHHHH RRRR EEE SSS HHHHH O O L D D %
% T H H R R E SS H H O O L D D %
% T H H R R EEEEE SSSSS H H OOO LLLLL DDDD %
% %
% %
% MagickCore Image Threshold Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% 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/property.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache-view.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/configure.h"
#include "MagickCore/constitute.h"
#include "MagickCore/decorate.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/effect.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/montage.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/shear.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
Define declarations.
*/
#define ThresholdsFilename "thresholds.xml"
/*
Typedef declarations.
*/
struct _ThresholdMap
{
char
*map_id,
*description;
size_t
width,
height;
ssize_t
divisor,
*levels;
};
/*
Static declarations.
*/
static const char
*MinimalThresholdMap =
"<?xml version=\"1.0\"?>"
"<thresholds>"
" <threshold map=\"threshold\" alias=\"1x1\">"
" <description>Threshold 1x1 (non-dither)</description>"
" <levels width=\"1\" height=\"1\" divisor=\"2\">"
" 1"
" </levels>"
" </threshold>"
" <threshold map=\"checks\" alias=\"2x1\">"
" <description>Checkerboard 2x1 (dither)</description>"
" <levels width=\"2\" height=\"2\" divisor=\"3\">"
" 1 2"
" 2 1"
" </levels>"
" </threshold>"
"</thresholds>";
/*
Forward declarations.
*/
static ThresholdMap
*GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveThresholdImage() selects an individual threshold for each pixel
% based on the range of intensity values in its local neighborhood. This
% allows for thresholding of an image whose global intensity histogram
% doesn't contain distinctive peaks.
%
% The format of the AdaptiveThresholdImage method is:
%
% Image *AdaptiveThresholdImage(const Image *image,const size_t width,
% const size_t height,const double bias,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the local neighborhood.
%
% o height: the height of the local neighborhood.
%
% o bias: the mean bias.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
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);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoThresholdImage() automatically performs image thresholding
% dependent on which method you specify.
%
% The format of the AutoThresholdImage method is:
%
% MagickBooleanType AutoThresholdImage(Image *image,
% const AutoThresholdMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-threshold.
%
% o method: choose from Kapur, OTSU, or Triangle.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double KapurThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
#define MaxIntensity 255
double
*black_entropy,
*cumulative_histogram,
entropy,
epsilon,
maximum_entropy,
*white_entropy;
register ssize_t
i,
j;
size_t
threshold;
/*
Compute optimal threshold from the entopy of the histogram.
*/
cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*cumulative_histogram));
black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*black_entropy));
white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*white_entropy));
if ((cumulative_histogram == (double *) NULL) ||
(black_entropy == (double *) NULL) || (white_entropy == (double *) NULL))
{
if (white_entropy != (double *) NULL)
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
if (black_entropy != (double *) NULL)
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
if (cumulative_histogram != (double *) NULL)
cumulative_histogram=(double *)
RelinquishMagickMemory(cumulative_histogram);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Entropy for black and white parts of the histogram.
*/
cumulative_histogram[0]=histogram[0];
for (i=1; i <= MaxIntensity; i++)
cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i];
epsilon=MagickMinimumValue;
for (j=0; j <= MaxIntensity; j++)
{
/*
Black entropy.
*/
black_entropy[j]=0.0;
if (cumulative_histogram[j] > epsilon)
{
entropy=0.0;
for (i=0; i <= j; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/cumulative_histogram[j]*
log(histogram[i]/cumulative_histogram[j]);
black_entropy[j]=entropy;
}
/*
White entropy.
*/
white_entropy[j]=0.0;
if ((1.0-cumulative_histogram[j]) > epsilon)
{
entropy=0.0;
for (i=j+1; i <= MaxIntensity; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/(1.0-cumulative_histogram[j])*
log(histogram[i]/(1.0-cumulative_histogram[j]));
white_entropy[j]=entropy;
}
}
/*
Find histogram bin with maximum entropy.
*/
maximum_entropy=black_entropy[0]+white_entropy[0];
threshold=0;
for (j=1; j <= MaxIntensity; j++)
if ((black_entropy[j]+white_entropy[j]) > maximum_entropy)
{
maximum_entropy=black_entropy[j]+white_entropy[j];
threshold=(size_t) j;
}
/*
Free resources.
*/
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram);
return(100.0*threshold/MaxIntensity);
}
static double OTSUThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
double
max_sigma,
*myu,
*omega,
*probability,
*sigma,
threshold;
register ssize_t
i;
/*
Compute optimal threshold from maximization of inter-class variance.
*/
myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu));
omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega));
probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*probability));
sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma));
if ((myu == (double *) NULL) || (omega == (double *) NULL) ||
(probability == (double *) NULL) || (sigma == (double *) NULL))
{
if (sigma != (double *) NULL)
sigma=(double *) RelinquishMagickMemory(sigma);
if (probability != (double *) NULL)
probability=(double *) RelinquishMagickMemory(probability);
if (omega != (double *) NULL)
omega=(double *) RelinquishMagickMemory(omega);
if (myu != (double *) NULL)
myu=(double *) RelinquishMagickMemory(myu);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Calculate probability density.
*/
for (i=0; i <= (ssize_t) MaxIntensity; i++)
probability[i]=histogram[i];
/*
Generate probability of graylevels and mean value for separation.
*/
omega[0]=probability[0];
myu[0]=0.0;
for (i=1; i <= (ssize_t) MaxIntensity; i++)
{
omega[i]=omega[i-1]+probability[i];
myu[i]=myu[i-1]+i*probability[i];
}
/*
Sigma maximization: inter-class variance and compute optimal threshold.
*/
threshold=0;
max_sigma=0.0;
for (i=0; i < (ssize_t) MaxIntensity; i++)
{
sigma[i]=0.0;
if ((omega[i] != 0.0) && (omega[i] != 1.0))
sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0-
omega[i]));
if (sigma[i] > max_sigma)
{
max_sigma=sigma[i];
threshold=(double) i;
}
}
/*
Free resources.
*/
myu=(double *) RelinquishMagickMemory(myu);
omega=(double *) RelinquishMagickMemory(omega);
probability=(double *) RelinquishMagickMemory(probability);
sigma=(double *) RelinquishMagickMemory(sigma);
return(100.0*threshold/MaxIntensity);
}
static double TriangleThreshold(const double *histogram)
{
double
a,
b,
c,
count,
distance,
inverse_ratio,
max_distance,
segment,
x1,
x2,
y1,
y2;
register ssize_t
i;
ssize_t
end,
max,
start,
threshold;
/*
Compute optimal threshold with triangle algorithm.
*/
start=0; /* find start bin, first bin not zero count */
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > 0.0)
{
start=i;
break;
}
end=0; /* find end bin, last bin not zero count */
for (i=(ssize_t) MaxIntensity; i >= 0; i--)
if (histogram[i] > 0.0)
{
end=i;
break;
}
max=0; /* find max bin, bin with largest count */
count=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > count)
{
max=i;
count=histogram[i];
}
/*
Compute threshold at split point.
*/
x1=(double) max;
y1=histogram[max];
x2=(double) end;
if ((max-start) >= (end-max))
x2=(double) start;
y2=0.0;
a=y1-y2;
b=x2-x1;
c=(-1.0)*(a*x1+b*y1);
inverse_ratio=1.0/sqrt(a*a+b*b+c*c);
threshold=0;
max_distance=0.0;
if (x2 == (double) start)
for (i=start; i < max; i++)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment > 0.0))
{
threshold=i;
max_distance=distance;
}
}
else
for (i=end; i > max; i--)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment < 0.0))
{
threshold=i;
max_distance=distance;
}
}
return(100.0*threshold/MaxIntensity);
}
MagickExport MagickBooleanType AutoThresholdImage(Image *image,
const AutoThresholdMethod method,ExceptionInfo *exception)
{
CacheView
*image_view;
char
property[MagickPathExtent];
double
gamma,
*histogram,
sum,
threshold;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
y;
/*
Form histogram.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
(void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
double intensity = GetPixelIntensity(image,p);
histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Normalize histogram.
*/
sum=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
sum+=histogram[i];
gamma=PerceptibleReciprocal(sum);
for (i=0; i <= (ssize_t) MaxIntensity; i++)
histogram[i]=gamma*histogram[i];
/*
Discover threshold from histogram.
*/
switch (method)
{
case KapurThresholdMethod:
{
threshold=KapurThreshold(image,histogram,exception);
break;
}
case OTSUThresholdMethod:
default:
{
threshold=OTSUThreshold(image,histogram,exception);
break;
}
case TriangleThresholdMethod:
{
threshold=TriangleThreshold(histogram);
break;
}
}
histogram=(double *) RelinquishMagickMemory(histogram);
if (threshold < 0.0)
status=MagickFalse;
if (status == MagickFalse)
return(MagickFalse);
/*
Threshold image.
*/
(void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold);
(void) SetImageProperty(image,"auto-threshold:threshold",property,exception);
return(BilevelImage(image,QuantumRange*threshold/100.0,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B i l e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BilevelImage() changes the value of individual pixels based on the
% intensity of each pixel channel. The result is a high-contrast image.
%
% More precisely each channel value of the image is 'thresholded' so that if
% it is equal to or less than the given value it is set to zero, while any
% value greater than that give is set to it maximum or QuantumRange.
%
% This function is what is used to implement the "-threshold" operator for
% the command line API.
%
% If the default channel setting is given the image is thresholded using just
% the gray 'intensity' of the image, rather than the individual channels.
%
% The format of the BilevelImage method is:
%
% MagickBooleanType BilevelImage(Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: define the threshold values.
%
% o exception: return any errors or warnings in this structure.
%
% Aside: You can get the same results as operator using LevelImages()
% with the 'threshold' value for both the black_point and the white_point.
%
*/
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
/*
Bilevel threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l a c k T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlackThresholdImage() is like ThresholdImage() but forces all pixels below
% the threshold into black while leaving all pixels at or above the threshold
% unchanged.
%
% The format of the BlackThresholdImage method is:
%
% MagickBooleanType BlackThresholdImage(Image *image,
% const char *threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
GetPixelInfo(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.rho;
threshold.blue=geometry_info.rho;
threshold.black=geometry_info.rho;
threshold.alpha=100.0;
if ((flags & SigmaValue) != 0)
threshold.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
threshold.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
threshold.alpha=geometry_info.psi;
if (threshold.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
threshold.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
threshold.alpha=geometry_info.chi;
}
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.black*=(MagickRealType) (QuantumRange/100.0);
threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
}
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel < GetPixelInfoChannel(&threshold,channel))
q[i]=(Quantum) 0;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l a m p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampImage() set each pixel whose value is below zero to zero and any the
% pixel whose value is above the quantum range to the quantum range (e.g.
% 65535) otherwise the pixel value remains unchanged.
%
% The format of the ClampImage method is:
%
% MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
{
#define ClampImageTag "Clamp/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelInfo
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
q->red=(double) ClampPixel(q->red);
q->green=(double) ClampPixel(q->green);
q->blue=(double) ClampPixel(q->blue);
q->alpha=(double) ClampPixel(q->alpha);
q++;
}
return(SyncImage(image,exception));
}
/*
Clamp image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampPixel((MagickRealType) q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ClampImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyThresholdMap() de-allocate the given ThresholdMap
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *DestroyThresholdMap(Threshold *map)
%
% A description of each parameter follows.
%
% o map: Pointer to the Threshold map to destroy
%
*/
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
{
assert(map != (ThresholdMap *) NULL);
if (map->map_id != (char *) NULL)
map->map_id=DestroyString(map->map_id);
if (map->description != (char *) NULL)
map->description=DestroyString(map->description);
if (map->levels != (ssize_t *) NULL)
map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
map=(ThresholdMap *) RelinquishMagickMemory(map);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMap() loads and searches one or more threshold map files for the
% map matching the given name or alias.
%
% The format of the GetThresholdMap method is:
%
% ThresholdMap *GetThresholdMap(const char *map_id,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o map_id: ID of the map to look for.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
ExceptionInfo *exception)
{
ThresholdMap
*map;
map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
{
const StringInfo
*option;
LinkedListInfo
*options;
options=GetConfigureOptions(ThresholdsFilename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),map_id,exception);
if (map != (ThresholdMap *) NULL)
break;
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
}
#endif
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMapFile() look for a given threshold map name or alias in the
% given XML file data, and return the allocated the map when found.
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
% const char *map_id,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o map_id: ID of the map to look for in XML list.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename,
const char *map_id,ExceptionInfo *exception)
{
char
*p;
const char
*attribute,
*content;
double
value;
register ssize_t
i;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
map=(ThresholdMap *) NULL;
thresholds=NewXMLTree(xml,exception);
if (thresholds == (XMLTreeInfo *) NULL)
return(map);
for (threshold=GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold=GetNextXMLTreeTag(threshold))
{
attribute=GetXMLTreeAttribute(threshold,"map");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(threshold,"alias");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
}
if (threshold == (XMLTreeInfo *) NULL)
{
thresholds=DestroyXMLTree(thresholds);
return(map);
}
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
levels=GetXMLTreeChild(threshold,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map));
map->map_id=(char *) NULL;
map->description=(char *) NULL;
map->levels=(ssize_t *) NULL;
attribute=GetXMLTreeAttribute(threshold,"map");
if (attribute != (char *) NULL)
map->map_id=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
map->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->width=StringToUnsignedLong(attribute);
if (map->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->height=StringToUnsignedLong(attribute);
if (map->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->divisor=(ssize_t) StringToLong(attribute);
if (map->divisor < 2)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if (map->levels == (ssize_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
for (i=0; i < (ssize_t) (map->width*map->height); i++)
{
map->levels[i]=(ssize_t) strtol(content,&p,10);
if (p == content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L i s t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMapFile() lists the threshold maps and their descriptions
% in the given XML file data.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
% const char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
const char *filename,ExceptionInfo *exception)
{
const char
*alias,
*content,
*map;
XMLTreeInfo
*description,
*threshold,
*thresholds;
assert( xml != (char *) NULL );
assert( file != (FILE *) NULL );
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(MagickFalse);
(void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
(void) FormatLocaleFile(file,
"----------------------------------------------------\n");
threshold=GetXMLTreeChild(thresholds,"threshold");
for ( ; threshold != (XMLTreeInfo *) NULL;
threshold=GetNextXMLTreeTag(threshold))
{
map=GetXMLTreeAttribute(threshold,"map");
if (map == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<map>");
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
alias=GetXMLTreeAttribute(threshold,"alias");
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"",map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
content=GetXMLTreeContent(description);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
content);
}
thresholds=DestroyXMLTree(thresholds);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t T h r e s h o l d M a p s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMaps() lists the threshold maps and their descriptions
% as defined by "threshold.xml" to a file.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
MagickStatusType
status;
status=MagickTrue;
if (file == (FILE *) NULL)
file=stdout;
options=GetConfigureOptions(ThresholdsFilename,exception);
(void) FormatLocaleFile(file,
"\n Threshold Maps for Ordered Dither Operations\n");
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
(void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedDitherImage() will perform a ordered dither based on a number
% of pre-defined dithering threshold maps, but over multiple intensity
% levels, which can be different for different channels, according to the
% input argument.
%
% The format of the OrderedDitherImage method is:
%
% MagickBooleanType OrderedDitherImage(Image *image,
% const char *threshold_map,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold_map: A string containing the name of the threshold dither
% map to use, followed by zero or more numbers representing the number
% of color levels tho dither between.
%
% Any level number less than 2 will be equivalent to 2, and means only
% binary dithering will be applied to each color channel.
%
% No numbers also means a 2 level (bitmap) dither will be applied to all
% channels, while a single number is the number of levels applied to each
% channel in sequence. More numbers will be applied in turn to each of
% the color channels.
%
% For example: "o3x3,6" will generate a 6 level posterization of the
% image with a ordered 3x3 diffused pixel dither being applied between
% each level. While checker,8,8,4 will produce a 332 colormaped image
% with only a single checkerboard hash pattern (50% grey) between each
% color level, to basically double the number of color levels with
% a bare minimim of dithering.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedDitherImage(Image *image,
const char *threshold_map,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
char
token[MagickPathExtent];
const char
*p;
double
levels[CompositePixelChannel];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
ThresholdMap
*map;
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);
if (threshold_map == (const char *) NULL)
return(MagickTrue);
p=(char *) threshold_map;
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
threshold_map=p;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0'))
{
if ((p-threshold_map) >= (MagickPathExtent-1))
break;
token[p-threshold_map]=(*p);
p++;
}
token[p-threshold_map]='\0';
map=GetThresholdMap(token,exception);
if (map == (ThresholdMap *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
return(MagickFalse);
}
for (i=0; i < MaxPixelChannels; i++)
levels[i]=2.0;
p=strchr((char *) threshold_map,',');
if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0))
{
GetNextToken(p,&p,MagickPathExtent,token);
for (i=0; (i < MaxPixelChannels); i++)
levels[i]=StringToDouble(token,(char **) NULL);
for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
levels[i]=StringToDouble(token,(char **) NULL);
}
}
for (i=0; i < MaxPixelChannels; i++)
if (fabs(levels[i]) >= 1)
levels[i]-=1.0;
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
ssize_t
n;
n=0;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
ssize_t
level,
threshold;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (fabs(levels[n]) < MagickEpsilon)
{
n++;
continue;
}
threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1));
level=threshold/(map->divisor-1);
threshold-=level*(map->divisor-1);
q[i]=ClampToQuantum((double) (level+(threshold >=
map->levels[(x % map->width)+map->width*(y % map->height)]))*
QuantumRange/levels[n]);
n++;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,DitherImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
map=DestroyThresholdMap(map);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P e r c e p t i b l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PerceptibleImage() set each pixel whose value is less than |epsilon| to
% epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
% unchanged.
%
% The format of the PerceptibleImage method is:
%
% MagickBooleanType PerceptibleImage(Image *image,const double epsilon,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o epsilon: the epsilon threshold (e.g. 1.0e-9).
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PerceptibleThreshold(const Quantum quantum,
const double epsilon)
{
double
sign;
sign=(double) quantum < 0.0 ? -1.0 : 1.0;
if ((sign*quantum) >= epsilon)
return(quantum);
return((Quantum) (sign*epsilon));
}
MagickExport MagickBooleanType PerceptibleImage(Image *image,
const double epsilon,ExceptionInfo *exception)
{
#define PerceptibleImageTag "Perceptible/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelInfo
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red),
epsilon);
q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green),
epsilon);
q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue),
epsilon);
q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha),
epsilon);
q++;
}
return(SyncImage(image,exception));
}
/*
Perceptible image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PerceptibleThreshold(q[i],epsilon);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,PerceptibleImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n d o m T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RandomThresholdImage() changes the value of individual pixels based on the
% intensity of each pixel compared to a random threshold. The result is a
% low-contrast, two color image.
%
% The format of the RandomThresholdImage method is:
%
% MagickBooleanType RandomThresholdImage(Image *image,
% const char *thresholds,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low,high: Specify the high and low thresholds. These values range from
% 0 to QuantumRange.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
const double min_threshold, const double max_threshold,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
GetPixelInfo(image,&threshold);
/*
Random threshold image.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
threshold;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((double) q[i] < min_threshold)
threshold=min_threshold;
else
if ((double) q[i] > max_threshold)
threshold=max_threshold;
else
threshold=(double) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
q[i]=(double) q[i] <= threshold ? 0 : QuantumRange;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n g e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RangeThresholdImage() applies soft and hard thresholding.
%
% The format of the RangeThresholdImage method is:
%
% MagickBooleanType RangeThresholdImage(Image *image,
% const double low_black,const double low_white,const double high_white,
% const double high_black,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low_black: Define the minimum black threshold value.
%
% o low_white: Define the minimum white threshold value.
%
% o high_white: Define the maximum white threshold value.
%
% o high_black: Define the maximum black threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RangeThresholdImage(Image *image,
const double low_black,const double low_white,const double high_white,
const double high_black,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Range threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel < low_black)
q[i]=0;
else
if ((pixel >= low_black) && (pixel < low_white))
q[i]=ClampToQuantum(QuantumRange*
PerceptibleReciprocal(low_white-low_black)*(pixel-low_black));
else
if ((pixel >= low_white) && (pixel <= high_white))
q[i]=QuantumRange;
else
if ((pixel > high_white) && (pixel <= high_black))
q[i]=ClampToQuantum(QuantumRange*PerceptibleReciprocal(
high_black-high_white)*(high_black-pixel));
else
if (pixel > high_black)
q[i]=0;
else
q[i]=0;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W h i t e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
% the threshold into white while leaving all pixels at or below the threshold
% unchanged.
%
% The format of the WhiteThresholdImage method is:
%
% MagickBooleanType WhiteThresholdImage(Image *image,
% const char *threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
GetPixelInfo(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.rho;
threshold.blue=geometry_info.rho;
threshold.black=geometry_info.rho;
threshold.alpha=100.0;
if ((flags & SigmaValue) != 0)
threshold.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
threshold.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
threshold.alpha=geometry_info.psi;
if (threshold.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
threshold.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
threshold.alpha=geometry_info.chi;
}
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.black*=(MagickRealType) (QuantumRange/100.0);
threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
}
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel > GetPixelInfoChannel(&threshold,channel))
q[i]=QuantumRange;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_922_0 |
crossvul-cpp_data_good_3176_0 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* The IP to API glue.
*
* Authors: see ip.c
*
* Fixes:
* Many : Split from ip.c , see ip.c for history.
* Martin Mares : TOS setting fixed.
* Alan Cox : Fixed a couple of oopses in Martin's
* TOS tweaks.
* Mike McLagan : Routing by source
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/icmp.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/tcp_states.h>
#include <linux/udp.h>
#include <linux/igmp.h>
#include <linux/netfilter.h>
#include <linux/route.h>
#include <linux/mroute.h>
#include <net/inet_ecn.h>
#include <net/route.h>
#include <net/xfrm.h>
#include <net/compat.h>
#include <net/checksum.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <net/transp_v6.h>
#endif
#include <net/ip_fib.h>
#include <linux/errqueue.h>
#include <linux/uaccess.h>
/*
* SOL_IP control messages.
*/
static void ip_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
{
struct in_pktinfo info = *PKTINFO_SKB_CB(skb);
info.ipi_addr.s_addr = ip_hdr(skb)->daddr;
put_cmsg(msg, SOL_IP, IP_PKTINFO, sizeof(info), &info);
}
static void ip_cmsg_recv_ttl(struct msghdr *msg, struct sk_buff *skb)
{
int ttl = ip_hdr(skb)->ttl;
put_cmsg(msg, SOL_IP, IP_TTL, sizeof(int), &ttl);
}
static void ip_cmsg_recv_tos(struct msghdr *msg, struct sk_buff *skb)
{
put_cmsg(msg, SOL_IP, IP_TOS, 1, &ip_hdr(skb)->tos);
}
static void ip_cmsg_recv_opts(struct msghdr *msg, struct sk_buff *skb)
{
if (IPCB(skb)->opt.optlen == 0)
return;
put_cmsg(msg, SOL_IP, IP_RECVOPTS, IPCB(skb)->opt.optlen,
ip_hdr(skb) + 1);
}
static void ip_cmsg_recv_retopts(struct msghdr *msg, struct sk_buff *skb)
{
unsigned char optbuf[sizeof(struct ip_options) + 40];
struct ip_options *opt = (struct ip_options *)optbuf;
if (IPCB(skb)->opt.optlen == 0)
return;
if (ip_options_echo(opt, skb)) {
msg->msg_flags |= MSG_CTRUNC;
return;
}
ip_options_undo(opt);
put_cmsg(msg, SOL_IP, IP_RETOPTS, opt->optlen, opt->__data);
}
static void ip_cmsg_recv_fragsize(struct msghdr *msg, struct sk_buff *skb)
{
int val;
if (IPCB(skb)->frag_max_size == 0)
return;
val = IPCB(skb)->frag_max_size;
put_cmsg(msg, SOL_IP, IP_RECVFRAGSIZE, sizeof(val), &val);
}
static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,
int tlen, int offset)
{
__wsum csum = skb->csum;
if (skb->ip_summed != CHECKSUM_COMPLETE)
return;
if (offset != 0) {
int tend_off = skb_transport_offset(skb) + tlen;
csum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0));
}
put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);
}
static void ip_cmsg_recv_security(struct msghdr *msg, struct sk_buff *skb)
{
char *secdata;
u32 seclen, secid;
int err;
err = security_socket_getpeersec_dgram(NULL, skb, &secid);
if (err)
return;
err = security_secid_to_secctx(secid, &secdata, &seclen);
if (err)
return;
put_cmsg(msg, SOL_IP, SCM_SECURITY, seclen, secdata);
security_release_secctx(secdata, seclen);
}
static void ip_cmsg_recv_dstaddr(struct msghdr *msg, struct sk_buff *skb)
{
struct sockaddr_in sin;
const struct iphdr *iph = ip_hdr(skb);
__be16 *ports = (__be16 *)skb_transport_header(skb);
if (skb_transport_offset(skb) + 4 > (int)skb->len)
return;
/* All current transport protocols have the port numbers in the
* first four bytes of the transport header and this function is
* written with this assumption in mind.
*/
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = iph->daddr;
sin.sin_port = ports[1];
memset(sin.sin_zero, 0, sizeof(sin.sin_zero));
put_cmsg(msg, SOL_IP, IP_ORIGDSTADDR, sizeof(sin), &sin);
}
void ip_cmsg_recv_offset(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb, int tlen, int offset)
{
struct inet_sock *inet = inet_sk(sk);
unsigned int flags = inet->cmsg_flags;
/* Ordered by supposed usage frequency */
if (flags & IP_CMSG_PKTINFO) {
ip_cmsg_recv_pktinfo(msg, skb);
flags &= ~IP_CMSG_PKTINFO;
if (!flags)
return;
}
if (flags & IP_CMSG_TTL) {
ip_cmsg_recv_ttl(msg, skb);
flags &= ~IP_CMSG_TTL;
if (!flags)
return;
}
if (flags & IP_CMSG_TOS) {
ip_cmsg_recv_tos(msg, skb);
flags &= ~IP_CMSG_TOS;
if (!flags)
return;
}
if (flags & IP_CMSG_RECVOPTS) {
ip_cmsg_recv_opts(msg, skb);
flags &= ~IP_CMSG_RECVOPTS;
if (!flags)
return;
}
if (flags & IP_CMSG_RETOPTS) {
ip_cmsg_recv_retopts(msg, skb);
flags &= ~IP_CMSG_RETOPTS;
if (!flags)
return;
}
if (flags & IP_CMSG_PASSSEC) {
ip_cmsg_recv_security(msg, skb);
flags &= ~IP_CMSG_PASSSEC;
if (!flags)
return;
}
if (flags & IP_CMSG_ORIGDSTADDR) {
ip_cmsg_recv_dstaddr(msg, skb);
flags &= ~IP_CMSG_ORIGDSTADDR;
if (!flags)
return;
}
if (flags & IP_CMSG_CHECKSUM)
ip_cmsg_recv_checksum(msg, skb, tlen, offset);
if (flags & IP_CMSG_RECVFRAGSIZE)
ip_cmsg_recv_fragsize(msg, skb);
}
EXPORT_SYMBOL(ip_cmsg_recv_offset);
int ip_cmsg_send(struct sock *sk, struct msghdr *msg, struct ipcm_cookie *ipc,
bool allow_ipv6)
{
int err, val;
struct cmsghdr *cmsg;
struct net *net = sock_net(sk);
for_each_cmsghdr(cmsg, msg) {
if (!CMSG_OK(msg, cmsg))
return -EINVAL;
#if IS_ENABLED(CONFIG_IPV6)
if (allow_ipv6 &&
cmsg->cmsg_level == SOL_IPV6 &&
cmsg->cmsg_type == IPV6_PKTINFO) {
struct in6_pktinfo *src_info;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(*src_info)))
return -EINVAL;
src_info = (struct in6_pktinfo *)CMSG_DATA(cmsg);
if (!ipv6_addr_v4mapped(&src_info->ipi6_addr))
return -EINVAL;
ipc->oif = src_info->ipi6_ifindex;
ipc->addr = src_info->ipi6_addr.s6_addr32[3];
continue;
}
#endif
if (cmsg->cmsg_level == SOL_SOCKET) {
err = __sock_cmsg_send(sk, msg, cmsg, &ipc->sockc);
if (err)
return err;
continue;
}
if (cmsg->cmsg_level != SOL_IP)
continue;
switch (cmsg->cmsg_type) {
case IP_RETOPTS:
err = cmsg->cmsg_len - sizeof(struct cmsghdr);
/* Our caller is responsible for freeing ipc->opt */
err = ip_options_get(net, &ipc->opt, CMSG_DATA(cmsg),
err < 40 ? err : 40);
if (err)
return err;
break;
case IP_PKTINFO:
{
struct in_pktinfo *info;
if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct in_pktinfo)))
return -EINVAL;
info = (struct in_pktinfo *)CMSG_DATA(cmsg);
ipc->oif = info->ipi_ifindex;
ipc->addr = info->ipi_spec_dst.s_addr;
break;
}
case IP_TTL:
if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)))
return -EINVAL;
val = *(int *)CMSG_DATA(cmsg);
if (val < 1 || val > 255)
return -EINVAL;
ipc->ttl = val;
break;
case IP_TOS:
if (cmsg->cmsg_len == CMSG_LEN(sizeof(int)))
val = *(int *)CMSG_DATA(cmsg);
else if (cmsg->cmsg_len == CMSG_LEN(sizeof(u8)))
val = *(u8 *)CMSG_DATA(cmsg);
else
return -EINVAL;
if (val < 0 || val > 255)
return -EINVAL;
ipc->tos = val;
ipc->priority = rt_tos2priority(ipc->tos);
break;
default:
return -EINVAL;
}
}
return 0;
}
/* Special input handler for packets caught by router alert option.
They are selected only by protocol field, and then processed likely
local ones; but only if someone wants them! Otherwise, router
not running rsvpd will kill RSVP.
It is user level problem, what it will make with them.
I have no idea, how it will masquearde or NAT them (it is joke, joke :-)),
but receiver should be enough clever f.e. to forward mtrace requests,
sent to multicast group to reach destination designated router.
*/
struct ip_ra_chain __rcu *ip_ra_chain;
static DEFINE_SPINLOCK(ip_ra_lock);
static void ip_ra_destroy_rcu(struct rcu_head *head)
{
struct ip_ra_chain *ra = container_of(head, struct ip_ra_chain, rcu);
sock_put(ra->saved_sk);
kfree(ra);
}
int ip_ra_control(struct sock *sk, unsigned char on,
void (*destructor)(struct sock *))
{
struct ip_ra_chain *ra, *new_ra;
struct ip_ra_chain __rcu **rap;
if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num == IPPROTO_RAW)
return -EINVAL;
new_ra = on ? kmalloc(sizeof(*new_ra), GFP_KERNEL) : NULL;
spin_lock_bh(&ip_ra_lock);
for (rap = &ip_ra_chain;
(ra = rcu_dereference_protected(*rap,
lockdep_is_held(&ip_ra_lock))) != NULL;
rap = &ra->next) {
if (ra->sk == sk) {
if (on) {
spin_unlock_bh(&ip_ra_lock);
kfree(new_ra);
return -EADDRINUSE;
}
/* dont let ip_call_ra_chain() use sk again */
ra->sk = NULL;
RCU_INIT_POINTER(*rap, ra->next);
spin_unlock_bh(&ip_ra_lock);
if (ra->destructor)
ra->destructor(sk);
/*
* Delay sock_put(sk) and kfree(ra) after one rcu grace
* period. This guarantee ip_call_ra_chain() dont need
* to mess with socket refcounts.
*/
ra->saved_sk = sk;
call_rcu(&ra->rcu, ip_ra_destroy_rcu);
return 0;
}
}
if (!new_ra) {
spin_unlock_bh(&ip_ra_lock);
return -ENOBUFS;
}
new_ra->sk = sk;
new_ra->destructor = destructor;
RCU_INIT_POINTER(new_ra->next, ra);
rcu_assign_pointer(*rap, new_ra);
sock_hold(sk);
spin_unlock_bh(&ip_ra_lock);
return 0;
}
void ip_icmp_error(struct sock *sk, struct sk_buff *skb, int err,
__be16 port, u32 info, u8 *payload)
{
struct sock_exterr_skb *serr;
skb = skb_clone(skb, GFP_ATOMIC);
if (!skb)
return;
serr = SKB_EXT_ERR(skb);
serr->ee.ee_errno = err;
serr->ee.ee_origin = SO_EE_ORIGIN_ICMP;
serr->ee.ee_type = icmp_hdr(skb)->type;
serr->ee.ee_code = icmp_hdr(skb)->code;
serr->ee.ee_pad = 0;
serr->ee.ee_info = info;
serr->ee.ee_data = 0;
serr->addr_offset = (u8 *)&(((struct iphdr *)(icmp_hdr(skb) + 1))->daddr) -
skb_network_header(skb);
serr->port = port;
if (skb_pull(skb, payload - skb->data)) {
skb_reset_transport_header(skb);
if (sock_queue_err_skb(sk, skb) == 0)
return;
}
kfree_skb(skb);
}
void ip_local_error(struct sock *sk, int err, __be32 daddr, __be16 port, u32 info)
{
struct inet_sock *inet = inet_sk(sk);
struct sock_exterr_skb *serr;
struct iphdr *iph;
struct sk_buff *skb;
if (!inet->recverr)
return;
skb = alloc_skb(sizeof(struct iphdr), GFP_ATOMIC);
if (!skb)
return;
skb_put(skb, sizeof(struct iphdr));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
iph->daddr = daddr;
serr = SKB_EXT_ERR(skb);
serr->ee.ee_errno = err;
serr->ee.ee_origin = SO_EE_ORIGIN_LOCAL;
serr->ee.ee_type = 0;
serr->ee.ee_code = 0;
serr->ee.ee_pad = 0;
serr->ee.ee_info = info;
serr->ee.ee_data = 0;
serr->addr_offset = (u8 *)&iph->daddr - skb_network_header(skb);
serr->port = port;
__skb_pull(skb, skb_tail_pointer(skb) - skb->data);
skb_reset_transport_header(skb);
if (sock_queue_err_skb(sk, skb))
kfree_skb(skb);
}
/* For some errors we have valid addr_offset even with zero payload and
* zero port. Also, addr_offset should be supported if port is set.
*/
static inline bool ipv4_datagram_support_addr(struct sock_exterr_skb *serr)
{
return serr->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
serr->ee.ee_origin == SO_EE_ORIGIN_LOCAL || serr->port;
}
/* IPv4 supports cmsg on all imcp errors and some timestamps
*
* Timestamp code paths do not initialize the fields expected by cmsg:
* the PKTINFO fields in skb->cb[]. Fill those in here.
*/
static bool ipv4_datagram_support_cmsg(const struct sock *sk,
struct sk_buff *skb,
int ee_origin)
{
struct in_pktinfo *info;
if (ee_origin == SO_EE_ORIGIN_ICMP)
return true;
if (ee_origin == SO_EE_ORIGIN_LOCAL)
return false;
/* Support IP_PKTINFO on tstamp packets if requested, to correlate
* timestamp with egress dev. Not possible for packets without dev
* or without payload (SOF_TIMESTAMPING_OPT_TSONLY).
*/
if ((!(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_CMSG)) ||
(!skb->dev))
return false;
info = PKTINFO_SKB_CB(skb);
info->ipi_spec_dst.s_addr = ip_hdr(skb)->saddr;
info->ipi_ifindex = skb->dev->ifindex;
return true;
}
/*
* Handle MSG_ERRQUEUE
*/
int ip_recv_error(struct sock *sk, struct msghdr *msg, int len, int *addr_len)
{
struct sock_exterr_skb *serr;
struct sk_buff *skb;
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct {
struct sock_extended_err ee;
struct sockaddr_in offender;
} errhdr;
int err;
int copied;
WARN_ON_ONCE(sk->sk_family == AF_INET6);
err = -EAGAIN;
skb = sock_dequeue_err_skb(sk);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (unlikely(err)) {
kfree_skb(skb);
return err;
}
sock_recv_timestamp(msg, sk, skb);
serr = SKB_EXT_ERR(skb);
if (sin && ipv4_datagram_support_addr(serr)) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = *(__be32 *)(skb_network_header(skb) +
serr->addr_offset);
sin->sin_port = serr->port;
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
memcpy(&errhdr.ee, &serr->ee, sizeof(struct sock_extended_err));
sin = &errhdr.offender;
memset(sin, 0, sizeof(*sin));
if (ipv4_datagram_support_cmsg(sk, skb, serr->ee.ee_origin)) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
if (inet_sk(sk)->cmsg_flags)
ip_cmsg_recv(msg, skb);
}
put_cmsg(msg, SOL_IP, IP_RECVERR, sizeof(errhdr), &errhdr);
/* Now we could try to dump offended packet options */
msg->msg_flags |= MSG_ERRQUEUE;
err = copied;
consume_skb(skb);
out:
return err;
}
/*
* Socket option code for IP. This is the end of the line after any
* TCP,UDP etc options on an IP socket.
*/
static bool setsockopt_needs_rtnl(int optname)
{
switch (optname) {
case IP_ADD_MEMBERSHIP:
case IP_ADD_SOURCE_MEMBERSHIP:
case IP_BLOCK_SOURCE:
case IP_DROP_MEMBERSHIP:
case IP_DROP_SOURCE_MEMBERSHIP:
case IP_MSFILTER:
case IP_UNBLOCK_SOURCE:
case MCAST_BLOCK_SOURCE:
case MCAST_MSFILTER:
case MCAST_JOIN_GROUP:
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_UNBLOCK_SOURCE:
return true;
}
return false;
}
static int do_ip_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
int val = 0, err;
bool needs_rtnl = setsockopt_needs_rtnl(optname);
switch (optname) {
case IP_PKTINFO:
case IP_RECVTTL:
case IP_RECVOPTS:
case IP_RECVTOS:
case IP_RETOPTS:
case IP_TOS:
case IP_TTL:
case IP_HDRINCL:
case IP_MTU_DISCOVER:
case IP_RECVERR:
case IP_ROUTER_ALERT:
case IP_FREEBIND:
case IP_PASSSEC:
case IP_TRANSPARENT:
case IP_MINTTL:
case IP_NODEFRAG:
case IP_BIND_ADDRESS_NO_PORT:
case IP_UNICAST_IF:
case IP_MULTICAST_TTL:
case IP_MULTICAST_ALL:
case IP_MULTICAST_LOOP:
case IP_RECVORIGDSTADDR:
case IP_CHECKSUM:
case IP_RECVFRAGSIZE:
if (optlen >= sizeof(int)) {
if (get_user(val, (int __user *) optval))
return -EFAULT;
} else if (optlen >= sizeof(char)) {
unsigned char ucval;
if (get_user(ucval, (unsigned char __user *) optval))
return -EFAULT;
val = (int) ucval;
}
}
/* If optlen==0, it is equivalent to val == 0 */
if (ip_mroute_opt(optname))
return ip_mroute_setsockopt(sk, optname, optval, optlen);
err = 0;
if (needs_rtnl)
rtnl_lock();
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
struct ip_options_rcu *old, *opt = NULL;
if (optlen > 40)
goto e_inval;
err = ip_options_get_from_user(sock_net(sk), &opt,
optval, optlen);
if (err)
break;
old = rcu_dereference_protected(inet->inet_opt,
lockdep_sock_is_held(sk));
if (inet->is_icsk) {
struct inet_connection_sock *icsk = inet_csk(sk);
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == PF_INET ||
(!((1 << sk->sk_state) &
(TCPF_LISTEN | TCPF_CLOSE)) &&
inet->inet_daddr != LOOPBACK4_IPV6)) {
#endif
if (old)
icsk->icsk_ext_hdr_len -= old->opt.optlen;
if (opt)
icsk->icsk_ext_hdr_len += opt->opt.optlen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
#if IS_ENABLED(CONFIG_IPV6)
}
#endif
}
rcu_assign_pointer(inet->inet_opt, opt);
if (old)
kfree_rcu(old, rcu);
break;
}
case IP_PKTINFO:
if (val)
inet->cmsg_flags |= IP_CMSG_PKTINFO;
else
inet->cmsg_flags &= ~IP_CMSG_PKTINFO;
break;
case IP_RECVTTL:
if (val)
inet->cmsg_flags |= IP_CMSG_TTL;
else
inet->cmsg_flags &= ~IP_CMSG_TTL;
break;
case IP_RECVTOS:
if (val)
inet->cmsg_flags |= IP_CMSG_TOS;
else
inet->cmsg_flags &= ~IP_CMSG_TOS;
break;
case IP_RECVOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RECVOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RECVOPTS;
break;
case IP_RETOPTS:
if (val)
inet->cmsg_flags |= IP_CMSG_RETOPTS;
else
inet->cmsg_flags &= ~IP_CMSG_RETOPTS;
break;
case IP_PASSSEC:
if (val)
inet->cmsg_flags |= IP_CMSG_PASSSEC;
else
inet->cmsg_flags &= ~IP_CMSG_PASSSEC;
break;
case IP_RECVORIGDSTADDR:
if (val)
inet->cmsg_flags |= IP_CMSG_ORIGDSTADDR;
else
inet->cmsg_flags &= ~IP_CMSG_ORIGDSTADDR;
break;
case IP_CHECKSUM:
if (val) {
if (!(inet->cmsg_flags & IP_CMSG_CHECKSUM)) {
inet_inc_convert_csum(sk);
inet->cmsg_flags |= IP_CMSG_CHECKSUM;
}
} else {
if (inet->cmsg_flags & IP_CMSG_CHECKSUM) {
inet_dec_convert_csum(sk);
inet->cmsg_flags &= ~IP_CMSG_CHECKSUM;
}
}
break;
case IP_RECVFRAGSIZE:
if (sk->sk_type != SOCK_RAW && sk->sk_type != SOCK_DGRAM)
goto e_inval;
if (val)
inet->cmsg_flags |= IP_CMSG_RECVFRAGSIZE;
else
inet->cmsg_flags &= ~IP_CMSG_RECVFRAGSIZE;
break;
case IP_TOS: /* This sets both TOS and Precedence */
if (sk->sk_type == SOCK_STREAM) {
val &= ~INET_ECN_MASK;
val |= inet->tos & INET_ECN_MASK;
}
if (inet->tos != val) {
inet->tos = val;
sk->sk_priority = rt_tos2priority(val);
sk_dst_reset(sk);
}
break;
case IP_TTL:
if (optlen < 1)
goto e_inval;
if (val != -1 && (val < 1 || val > 255))
goto e_inval;
inet->uc_ttl = val;
break;
case IP_HDRINCL:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->hdrincl = val ? 1 : 0;
break;
case IP_NODEFRAG:
if (sk->sk_type != SOCK_RAW) {
err = -ENOPROTOOPT;
break;
}
inet->nodefrag = val ? 1 : 0;
break;
case IP_BIND_ADDRESS_NO_PORT:
inet->bind_address_no_port = val ? 1 : 0;
break;
case IP_MTU_DISCOVER:
if (val < IP_PMTUDISC_DONT || val > IP_PMTUDISC_OMIT)
goto e_inval;
inet->pmtudisc = val;
break;
case IP_RECVERR:
inet->recverr = !!val;
if (!val)
skb_queue_purge(&sk->sk_error_queue);
break;
case IP_MULTICAST_TTL:
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
if (optlen < 1)
goto e_inval;
if (val == -1)
val = 1;
if (val < 0 || val > 255)
goto e_inval;
inet->mc_ttl = val;
break;
case IP_MULTICAST_LOOP:
if (optlen < 1)
goto e_inval;
inet->mc_loop = !!val;
break;
case IP_UNICAST_IF:
{
struct net_device *dev = NULL;
int ifindex;
if (optlen != sizeof(int))
goto e_inval;
ifindex = (__force int)ntohl((__force __be32)val);
if (ifindex == 0) {
inet->uc_index = 0;
err = 0;
break;
}
dev = dev_get_by_index(sock_net(sk), ifindex);
err = -EADDRNOTAVAIL;
if (!dev)
break;
dev_put(dev);
err = -EINVAL;
if (sk->sk_bound_dev_if)
break;
inet->uc_index = ifindex;
err = 0;
break;
}
case IP_MULTICAST_IF:
{
struct ip_mreqn mreq;
struct net_device *dev = NULL;
int midx;
if (sk->sk_type == SOCK_STREAM)
goto e_inval;
/*
* Check the arguments are allowable
*/
if (optlen < sizeof(struct in_addr))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (optlen >= sizeof(struct ip_mreq)) {
if (copy_from_user(&mreq, optval,
sizeof(struct ip_mreq)))
break;
} else if (optlen >= sizeof(struct in_addr)) {
if (copy_from_user(&mreq.imr_address, optval,
sizeof(struct in_addr)))
break;
}
}
if (!mreq.imr_ifindex) {
if (mreq.imr_address.s_addr == htonl(INADDR_ANY)) {
inet->mc_index = 0;
inet->mc_addr = 0;
err = 0;
break;
}
dev = ip_dev_find(sock_net(sk), mreq.imr_address.s_addr);
if (dev)
mreq.imr_ifindex = dev->ifindex;
} else
dev = dev_get_by_index(sock_net(sk), mreq.imr_ifindex);
err = -EADDRNOTAVAIL;
if (!dev)
break;
midx = l3mdev_master_ifindex(dev);
dev_put(dev);
err = -EINVAL;
if (sk->sk_bound_dev_if &&
mreq.imr_ifindex != sk->sk_bound_dev_if &&
(!midx || midx != sk->sk_bound_dev_if))
break;
inet->mc_index = mreq.imr_ifindex;
inet->mc_addr = mreq.imr_address.s_addr;
err = 0;
break;
}
case IP_ADD_MEMBERSHIP:
case IP_DROP_MEMBERSHIP:
{
struct ip_mreqn mreq;
err = -EPROTO;
if (inet_sk(sk)->is_icsk)
break;
if (optlen < sizeof(struct ip_mreq))
goto e_inval;
err = -EFAULT;
if (optlen >= sizeof(struct ip_mreqn)) {
if (copy_from_user(&mreq, optval, sizeof(mreq)))
break;
} else {
memset(&mreq, 0, sizeof(mreq));
if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq)))
break;
}
if (optname == IP_ADD_MEMBERSHIP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case IP_MSFILTER:
{
struct ip_msfilter *msf;
if (optlen < IP_MSFILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
msf = kmalloc(optlen, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(msf, optval, optlen)) {
kfree(msf);
break;
}
/* numsrc >= (1G-4) overflow in 32 bits */
if (msf->imsf_numsrc >= 0x3ffffffcU ||
msf->imsf_numsrc > net->ipv4.sysctl_igmp_max_msf) {
kfree(msf);
err = -ENOBUFS;
break;
}
if (IP_MSFILTER_SIZE(msf->imsf_numsrc) > optlen) {
kfree(msf);
err = -EINVAL;
break;
}
err = ip_mc_msfilter(sk, msf, 0);
kfree(msf);
break;
}
case IP_BLOCK_SOURCE:
case IP_UNBLOCK_SOURCE:
case IP_ADD_SOURCE_MEMBERSHIP:
case IP_DROP_SOURCE_MEMBERSHIP:
{
struct ip_mreq_source mreqs;
int omode, add;
if (optlen != sizeof(struct ip_mreq_source))
goto e_inval;
if (copy_from_user(&mreqs, optval, sizeof(mreqs))) {
err = -EFAULT;
break;
}
if (optname == IP_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == IP_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == IP_ADD_SOURCE_MEMBERSHIP) {
struct ip_mreqn mreq;
mreq.imr_multiaddr.s_addr = mreqs.imr_multiaddr;
mreq.imr_address.s_addr = mreqs.imr_interface;
mreq.imr_ifindex = 0;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
omode = MCAST_INCLUDE;
add = 1;
} else /* IP_DROP_SOURCE_MEMBERSHIP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs, 0);
break;
}
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct group_req greq;
struct sockaddr_in *psin;
struct ip_mreqn mreq;
if (optlen < sizeof(struct group_req))
goto e_inval;
err = -EFAULT;
if (copy_from_user(&greq, optval, sizeof(greq)))
break;
psin = (struct sockaddr_in *)&greq.gr_group;
if (psin->sin_family != AF_INET)
goto e_inval;
memset(&mreq, 0, sizeof(mreq));
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_ifindex = greq.gr_interface;
if (optname == MCAST_JOIN_GROUP)
err = ip_mc_join_group(sk, &mreq);
else
err = ip_mc_leave_group(sk, &mreq);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct group_source_req greqs;
struct ip_mreq_source mreqs;
struct sockaddr_in *psin;
int omode, add;
if (optlen != sizeof(struct group_source_req))
goto e_inval;
if (copy_from_user(&greqs, optval, sizeof(greqs))) {
err = -EFAULT;
break;
}
if (greqs.gsr_group.ss_family != AF_INET ||
greqs.gsr_source.ss_family != AF_INET) {
err = -EADDRNOTAVAIL;
break;
}
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreqs.imr_multiaddr = psin->sin_addr.s_addr;
psin = (struct sockaddr_in *)&greqs.gsr_source;
mreqs.imr_sourceaddr = psin->sin_addr.s_addr;
mreqs.imr_interface = 0; /* use index for mc_source */
if (optname == MCAST_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == MCAST_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == MCAST_JOIN_SOURCE_GROUP) {
struct ip_mreqn mreq;
psin = (struct sockaddr_in *)&greqs.gsr_group;
mreq.imr_multiaddr = psin->sin_addr;
mreq.imr_address.s_addr = 0;
mreq.imr_ifindex = greqs.gsr_interface;
err = ip_mc_join_group(sk, &mreq);
if (err && err != -EADDRINUSE)
break;
greqs.gsr_interface = mreq.imr_ifindex;
omode = MCAST_INCLUDE;
add = 1;
} else /* MCAST_LEAVE_SOURCE_GROUP */ {
omode = MCAST_INCLUDE;
add = 0;
}
err = ip_mc_source(add, omode, sk, &mreqs,
greqs.gsr_interface);
break;
}
case MCAST_MSFILTER:
{
struct sockaddr_in *psin;
struct ip_msfilter *msf = NULL;
struct group_filter *gsf = NULL;
int msize, i, ifindex;
if (optlen < GROUP_FILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
err = -ENOBUFS;
break;
}
gsf = kmalloc(optlen, GFP_KERNEL);
if (!gsf) {
err = -ENOBUFS;
break;
}
err = -EFAULT;
if (copy_from_user(gsf, optval, optlen))
goto mc_msf_out;
/* numsrc >= (4G-140)/128 overflow in 32 bits */
if (gsf->gf_numsrc >= 0x1ffffff ||
gsf->gf_numsrc > net->ipv4.sysctl_igmp_max_msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) {
err = -EINVAL;
goto mc_msf_out;
}
msize = IP_MSFILTER_SIZE(gsf->gf_numsrc);
msf = kmalloc(msize, GFP_KERNEL);
if (!msf) {
err = -ENOBUFS;
goto mc_msf_out;
}
ifindex = gsf->gf_interface;
psin = (struct sockaddr_in *)&gsf->gf_group;
if (psin->sin_family != AF_INET) {
err = -EADDRNOTAVAIL;
goto mc_msf_out;
}
msf->imsf_multiaddr = psin->sin_addr.s_addr;
msf->imsf_interface = 0;
msf->imsf_fmode = gsf->gf_fmode;
msf->imsf_numsrc = gsf->gf_numsrc;
err = -EADDRNOTAVAIL;
for (i = 0; i < gsf->gf_numsrc; ++i) {
psin = (struct sockaddr_in *)&gsf->gf_slist[i];
if (psin->sin_family != AF_INET)
goto mc_msf_out;
msf->imsf_slist[i] = psin->sin_addr.s_addr;
}
kfree(gsf);
gsf = NULL;
err = ip_mc_msfilter(sk, msf, ifindex);
mc_msf_out:
kfree(msf);
kfree(gsf);
break;
}
case IP_MULTICAST_ALL:
if (optlen < 1)
goto e_inval;
if (val != 0 && val != 1)
goto e_inval;
inet->mc_all = val;
break;
case IP_ROUTER_ALERT:
err = ip_ra_control(sk, val ? 1 : 0, NULL);
break;
case IP_FREEBIND:
if (optlen < 1)
goto e_inval;
inet->freebind = !!val;
break;
case IP_IPSEC_POLICY:
case IP_XFRM_POLICY:
err = -EPERM;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
break;
err = xfrm_user_policy(sk, optname, optval, optlen);
break;
case IP_TRANSPARENT:
if (!!val && !ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) &&
!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
err = -EPERM;
break;
}
if (optlen < 1)
goto e_inval;
inet->transparent = !!val;
break;
case IP_MINTTL:
if (optlen < 1)
goto e_inval;
if (val < 0 || val > 255)
goto e_inval;
inet->min_ttl = val;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
if (needs_rtnl)
rtnl_unlock();
return err;
e_inval:
release_sock(sk);
if (needs_rtnl)
rtnl_unlock();
return -EINVAL;
}
/**
* ipv4_pktinfo_prepare - transfer some info from rtable to skb
* @sk: socket
* @skb: buffer
*
* To support IP_CMSG_PKTINFO option, we store rt_iif and specific
* destination in skb->cb[] before dst drop.
* This way, receiver doesn't make cache line misses to read rtable.
*/
void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
/* We need to keep the dst for __ip_options_echo()
* We could restrict the test to opt.ts_needtime || opt.srr,
* but the following is good enough as IP options are not often used.
*/
if (unlikely(IPCB(skb)->opt.optlen))
skb_dst_force(skb);
else
skb_dst_drop(skb);
}
int ip_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
int err;
if (level != SOL_IP)
return -ENOPROTOOPT;
err = do_ip_setsockopt(sk, level, optname, optval, optlen);
#ifdef CONFIG_NETFILTER
/* we need to exclude all possible ENOPROTOOPTs except default case */
if (err == -ENOPROTOOPT && optname != IP_HDRINCL &&
optname != IP_IPSEC_POLICY &&
optname != IP_XFRM_POLICY &&
!ip_mroute_opt(optname)) {
lock_sock(sk);
err = nf_setsockopt(sk, PF_INET, optname, optval, optlen);
release_sock(sk);
}
#endif
return err;
}
EXPORT_SYMBOL(ip_setsockopt);
#ifdef CONFIG_COMPAT
int compat_ip_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
int err;
if (level != SOL_IP)
return -ENOPROTOOPT;
if (optname >= MCAST_JOIN_GROUP && optname <= MCAST_MSFILTER)
return compat_mc_setsockopt(sk, level, optname, optval, optlen,
ip_setsockopt);
err = do_ip_setsockopt(sk, level, optname, optval, optlen);
#ifdef CONFIG_NETFILTER
/* we need to exclude all possible ENOPROTOOPTs except default case */
if (err == -ENOPROTOOPT && optname != IP_HDRINCL &&
optname != IP_IPSEC_POLICY &&
optname != IP_XFRM_POLICY &&
!ip_mroute_opt(optname)) {
lock_sock(sk);
err = compat_nf_setsockopt(sk, PF_INET, optname,
optval, optlen);
release_sock(sk);
}
#endif
return err;
}
EXPORT_SYMBOL(compat_ip_setsockopt);
#endif
/*
* Get the options. Note for future reference. The GET of IP options gets
* the _received_ ones. The set sets the _sent_ ones.
*/
static bool getsockopt_needs_rtnl(int optname)
{
switch (optname) {
case IP_MSFILTER:
case MCAST_MSFILTER:
return true;
}
return false;
}
static int do_ip_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen, unsigned int flags)
{
struct inet_sock *inet = inet_sk(sk);
bool needs_rtnl = getsockopt_needs_rtnl(optname);
int val, err = 0;
int len;
if (level != SOL_IP)
return -EOPNOTSUPP;
if (ip_mroute_opt(optname))
return ip_mroute_getsockopt(sk, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
if (needs_rtnl)
rtnl_lock();
lock_sock(sk);
switch (optname) {
case IP_OPTIONS:
{
unsigned char optbuf[sizeof(struct ip_options)+40];
struct ip_options *opt = (struct ip_options *)optbuf;
struct ip_options_rcu *inet_opt;
inet_opt = rcu_dereference_protected(inet->inet_opt,
lockdep_sock_is_held(sk));
opt->optlen = 0;
if (inet_opt)
memcpy(optbuf, &inet_opt->opt,
sizeof(struct ip_options) +
inet_opt->opt.optlen);
release_sock(sk);
if (opt->optlen == 0)
return put_user(0, optlen);
ip_options_undo(opt);
len = min_t(unsigned int, len, opt->optlen);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, opt->__data, len))
return -EFAULT;
return 0;
}
case IP_PKTINFO:
val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0;
break;
case IP_RECVTTL:
val = (inet->cmsg_flags & IP_CMSG_TTL) != 0;
break;
case IP_RECVTOS:
val = (inet->cmsg_flags & IP_CMSG_TOS) != 0;
break;
case IP_RECVOPTS:
val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0;
break;
case IP_RETOPTS:
val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0;
break;
case IP_PASSSEC:
val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0;
break;
case IP_RECVORIGDSTADDR:
val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0;
break;
case IP_CHECKSUM:
val = (inet->cmsg_flags & IP_CMSG_CHECKSUM) != 0;
break;
case IP_RECVFRAGSIZE:
val = (inet->cmsg_flags & IP_CMSG_RECVFRAGSIZE) != 0;
break;
case IP_TOS:
val = inet->tos;
break;
case IP_TTL:
{
struct net *net = sock_net(sk);
val = (inet->uc_ttl == -1 ?
net->ipv4.sysctl_ip_default_ttl :
inet->uc_ttl);
break;
}
case IP_HDRINCL:
val = inet->hdrincl;
break;
case IP_NODEFRAG:
val = inet->nodefrag;
break;
case IP_BIND_ADDRESS_NO_PORT:
val = inet->bind_address_no_port;
break;
case IP_MTU_DISCOVER:
val = inet->pmtudisc;
break;
case IP_MTU:
{
struct dst_entry *dst;
val = 0;
dst = sk_dst_get(sk);
if (dst) {
val = dst_mtu(dst);
dst_release(dst);
}
if (!val) {
release_sock(sk);
return -ENOTCONN;
}
break;
}
case IP_RECVERR:
val = inet->recverr;
break;
case IP_MULTICAST_TTL:
val = inet->mc_ttl;
break;
case IP_MULTICAST_LOOP:
val = inet->mc_loop;
break;
case IP_UNICAST_IF:
val = (__force int)htonl((__u32) inet->uc_index);
break;
case IP_MULTICAST_IF:
{
struct in_addr addr;
len = min_t(unsigned int, len, sizeof(struct in_addr));
addr.s_addr = inet->mc_addr;
release_sock(sk);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &addr, len))
return -EFAULT;
return 0;
}
case IP_MSFILTER:
{
struct ip_msfilter msf;
if (len < IP_MSFILTER_SIZE(0)) {
err = -EINVAL;
goto out;
}
if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) {
err = -EFAULT;
goto out;
}
err = ip_mc_msfget(sk, &msf,
(struct ip_msfilter __user *)optval, optlen);
goto out;
}
case MCAST_MSFILTER:
{
struct group_filter gsf;
if (len < GROUP_FILTER_SIZE(0)) {
err = -EINVAL;
goto out;
}
if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) {
err = -EFAULT;
goto out;
}
err = ip_mc_gsfget(sk, &gsf,
(struct group_filter __user *)optval,
optlen);
goto out;
}
case IP_MULTICAST_ALL:
val = inet->mc_all;
break;
case IP_PKTOPTIONS:
{
struct msghdr msg;
release_sock(sk);
if (sk->sk_type != SOCK_STREAM)
return -ENOPROTOOPT;
msg.msg_control = (__force void *) optval;
msg.msg_controllen = len;
msg.msg_flags = flags;
if (inet->cmsg_flags & IP_CMSG_PKTINFO) {
struct in_pktinfo info;
info.ipi_addr.s_addr = inet->inet_rcv_saddr;
info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr;
info.ipi_ifindex = inet->mc_index;
put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info);
}
if (inet->cmsg_flags & IP_CMSG_TTL) {
int hlim = inet->mc_ttl;
put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim);
}
if (inet->cmsg_flags & IP_CMSG_TOS) {
int tos = inet->rcv_tos;
put_cmsg(&msg, SOL_IP, IP_TOS, sizeof(tos), &tos);
}
len -= msg.msg_controllen;
return put_user(len, optlen);
}
case IP_FREEBIND:
val = inet->freebind;
break;
case IP_TRANSPARENT:
val = inet->transparent;
break;
case IP_MINTTL:
val = inet->min_ttl;
break;
default:
release_sock(sk);
return -ENOPROTOOPT;
}
release_sock(sk);
if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) {
unsigned char ucval = (unsigned char)val;
len = 1;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &ucval, 1))
return -EFAULT;
} else {
len = min_t(unsigned int, sizeof(int), len);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
}
return 0;
out:
release_sock(sk);
if (needs_rtnl)
rtnl_unlock();
return err;
}
int ip_getsockopt(struct sock *sk, int level,
int optname, char __user *optval, int __user *optlen)
{
int err;
err = do_ip_getsockopt(sk, level, optname, optval, optlen, 0);
#ifdef CONFIG_NETFILTER
/* we need to exclude all possible ENOPROTOOPTs except default case */
if (err == -ENOPROTOOPT && optname != IP_PKTOPTIONS &&
!ip_mroute_opt(optname)) {
int len;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
err = nf_getsockopt(sk, PF_INET, optname, optval,
&len);
release_sock(sk);
if (err >= 0)
err = put_user(len, optlen);
return err;
}
#endif
return err;
}
EXPORT_SYMBOL(ip_getsockopt);
#ifdef CONFIG_COMPAT
int compat_ip_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int err;
if (optname == MCAST_MSFILTER)
return compat_mc_getsockopt(sk, level, optname, optval, optlen,
ip_getsockopt);
err = do_ip_getsockopt(sk, level, optname, optval, optlen,
MSG_CMSG_COMPAT);
#ifdef CONFIG_NETFILTER
/* we need to exclude all possible ENOPROTOOPTs except default case */
if (err == -ENOPROTOOPT && optname != IP_PKTOPTIONS &&
!ip_mroute_opt(optname)) {
int len;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
err = compat_nf_getsockopt(sk, PF_INET, optname, optval, &len);
release_sock(sk);
if (err >= 0)
err = put_user(len, optlen);
return err;
}
#endif
return err;
}
EXPORT_SYMBOL(compat_ip_getsockopt);
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3176_0 |
crossvul-cpp_data_good_2715_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/good_2715_0 |
crossvul-cpp_data_good_140_1 | /* radare - LGPL - Copyright 2011-2018 - earada, pancake */
#include <r_core.h>
#include "r_util.h"
#define DBSPATH "/share/radare2/" R2_VERSION "/fcnsign"
#define is_in_range(at, from, sz) ((at) >= (from) && (at) < ((from) + (sz)))
#define VA_FALSE 0
#define VA_TRUE 1
#define VA_NOREBASE 2
#define IS_MODE_SET(mode) (mode & R_CORE_BIN_SET)
#define IS_MODE_SIMPLE(mode) (mode & R_CORE_BIN_SIMPLE)
#define IS_MODE_SIMPLEST(mode) (mode & R_CORE_BIN_SIMPLEST)
#define IS_MODE_JSON(mode) (mode & R_CORE_BIN_JSON)
#define IS_MODE_RAD(mode) (mode & R_CORE_BIN_RADARE)
#define IS_MODE_NORMAL(mode) (!mode)
#define IS_MODE_CLASSDUMP(mode) (mode & R_CORE_BIN_CLASSDUMP)
// dup from cmd_info
#define PAIR_WIDTH 9
static void pair(const char *a, const char *b, int mode, bool last) {
if (!b || !*b) {
return;
}
if (IS_MODE_JSON (mode)) {
const char *lst = last ? "" : ",";
r_cons_printf ("\"%s\":%s%s", a, b, lst);
} else {
char ws[16];
int al = strlen (a);
if (al > PAIR_WIDTH) {
al = 0;
} else {
al = PAIR_WIDTH - al;
}
memset (ws, ' ', al);
ws[al] = 0;
r_cons_printf ("%s%s%s\n", a, ws, b);
}
}
static void pair_bool(const char *a, bool t, int mode, bool last) {
pair (a, r_str_bool (t), mode, last);
}
static void pair_int(const char *a, int n, int mode, bool last) {
pair (a, sdb_fmt ("%d", n), mode, last);
}
static void pair_ut64(const char *a, ut64 n, int mode, bool last) {
pair (a, sdb_fmt ("%"PFMT64d, n), mode, last);
}
static void pair_str(const char *a, const char *b, int mode, int last) {
if (IS_MODE_JSON (mode)) {
if (!b) {
b = "";
}
char *eb = r_str_utf16_encode (b, -1);
if (eb) {
char *qs = r_str_newf ("\"%s\"", eb);
pair (a, qs, mode, last);
free (eb);
free (qs);
}
} else {
pair (a, b, mode, last);
}
}
#define STR(x) (x)?(x):""
R_API int r_core_bin_set_cur (RCore *core, RBinFile *binfile);
static ut64 rva(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
if (va == VA_TRUE) {
return r_bin_get_vaddr (bin, paddr, vaddr);
}
if (va == VA_NOREBASE) {
return vaddr;
}
return paddr;
}
R_API int r_core_bin_set_by_fd(RCore *core, ut64 bin_fd) {
if (r_bin_file_set_cur_by_fd (core->bin, bin_fd)) {
r_core_bin_set_cur (core, r_core_bin_cur (core));
return true;
}
return false;
}
R_API int r_core_bin_set_by_name(RCore *core, const char * name) {
if (r_bin_file_set_cur_by_name (core->bin, name)) {
r_core_bin_set_cur (core, r_core_bin_cur (core));
return true;
}
return false;
}
R_API int r_core_bin_set_env(RCore *r, RBinFile *binfile) {
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
if (info) {
int va = info->has_va;
const char * arch = info->arch;
ut16 bits = info->bits;
ut64 baseaddr = r_bin_get_baddr (r->bin);
r_config_set_i (r->config, "bin.baddr", baseaddr);
r_config_set (r->config, "asm.arch", arch);
r_config_set_i (r->config, "asm.bits", bits);
r_config_set (r->config, "anal.arch", arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "anal.cpu", info->cpu);
} else {
r_config_set (r->config, "anal.cpu", arch);
}
r_asm_use (r->assembler, arch);
r_core_bin_info (r, R_CORE_BIN_ACC_ALL, R_CORE_BIN_SET, va, NULL, NULL);
r_core_bin_set_cur (r, binfile);
return true;
}
return false;
}
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile) {
if (!core->bin) {
return false;
}
if (!binfile) {
// Find first available binfile
ut32 fd = r_core_file_cur_fd (core);
binfile = fd != (ut32)-1
? r_bin_file_find_by_fd (core->bin, fd)
: NULL;
if (!binfile) {
return false;
}
}
r_bin_file_set_cur_binfile (core->bin, binfile);
return true;
}
R_API int r_core_bin_refresh_strings(RCore *r) {
return r_bin_reset_strings (r->bin) ? true: false;
}
R_API RBinFile * r_core_bin_cur(RCore *core) {
RBinFile *binfile = r_bin_cur (core->bin);
return binfile;
}
static void _print_strings(RCore *r, RList *list, int mode, int va) {
bool b64str = r_config_get_i (r->config, "bin.b64str");
int minstr = r_config_get_i (r->config, "bin.minstr");
int maxstr = r_config_get_i (r->config, "bin.maxstr");
RBin *bin = r->bin;
RBinObject *obj = r_bin_cur_object (bin);
RListIter *iter;
RListIter *last_processed = NULL;
RBinString *string;
RBinSection *section;
char *q;
bin->minstrlen = minstr;
bin->maxstrlen = maxstr;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs strings");
}
if (IS_MODE_SET (mode) && r_config_get_i (r->config, "bin.strings")) {
r_flag_space_set (r->flags, "strings");
r_cons_break_push (NULL, NULL);
}
RBinString b64 = {0};
r_list_foreach (list, iter, string) {
const char *section_name, *type_string;
ut64 paddr, vaddr, addr;
paddr = string->paddr;
vaddr = r_bin_get_vaddr (bin, paddr, string->vaddr);
addr = va ? vaddr : paddr;
if (!r_bin_string_filter (bin, string->string, addr)) {
continue;
}
if (string->length < minstr) {
continue;
}
if (maxstr && string->length > maxstr) {
continue;
}
section = r_bin_get_section_at (obj, paddr, 0);
section_name = section ? section->name : "";
type_string = r_bin_string_type (string->type);
if (b64str) {
ut8 *s = r_base64_decode_dyn (string->string, -1);
if (s && *s && IS_PRINTABLE (*s)) {
// TODO: add more checks
free (b64.string);
memcpy (&b64, string, sizeof (b64));
b64.string = (char *)s;
b64.size = strlen (b64.string);
string = &b64;
}
}
if (IS_MODE_SET (mode)) {
char *f_name, *str;
if (r_cons_is_breaked ()) {
break;
}
r_meta_add (r->anal, R_META_TYPE_STRING, addr, addr + string->size, string->string);
f_name = strdup (string->string);
r_name_filter (f_name, -1);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
} else {
str = r_str_newf ("str.%s", f_name);
}
r_flag_set (r->flags, str, addr, string->size);
free (str);
free (f_name);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%"PFMT64x" %d %d %s\n", addr,
string->size, string->length, string->string);
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_println (string->string);
} else if (IS_MODE_JSON (mode)) {
int *block_list;
q = r_base64_encode_dyn (string->string, -1);
r_cons_printf ("%s{\"vaddr\":%"PFMT64d
",\"paddr\":%"PFMT64d",\"ordinal\":%d"
",\"size\":%d,\"length\":%d,\"section\":\"%s\","
"\"type\":\"%s\",\"string\":\"%s\"",
last_processed ? ",": "",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, q);
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't include block list if
just Basic Latin (0x00 - 0x7F) */
break;
}
int *block_ptr = block_list;
r_cons_printf (",\"blocks\":[");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *utfName = r_utf_block_name (*block_ptr);
r_cons_printf ("\"%s\"", utfName? utfName: "");
}
r_cons_printf ("]");
R_FREE (block_list);
}
}
r_cons_printf ("}");
free (q);
} else if (IS_MODE_RAD (mode)) {
char *f_name, *str;
f_name = strdup (string->string);
r_name_filter (f_name, R_FLAG_NAME_SIZE);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
r_cons_printf ("f %s.str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
r->bin->prefix, f_name, string->size, addr,
string->size, addr);
} else {
str = r_str_newf ("str.%s", f_name);
r_cons_printf ("f str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
f_name, string->size, addr,
string->size, addr);
}
free (str);
free (f_name);
} else {
int *block_list;
char *str = string->string;
char *no_dbl_bslash_str = NULL;
if (!r->print->esc_bslash) {
char *ptr;
for (ptr = str; *ptr; ptr++) {
if (*ptr != '\\') {
continue;
}
if (*(ptr + 1) == '\\') {
if (!no_dbl_bslash_str) {
no_dbl_bslash_str = strdup (str);
if (!no_dbl_bslash_str) {
break;
}
ptr = no_dbl_bslash_str + (ptr - str);
}
memmove (ptr + 1, ptr + 2, strlen (ptr + 2) + 1);
}
}
if (no_dbl_bslash_str) {
str = no_dbl_bslash_str;
}
}
#if 0
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"
PFMT64x" ordinal=%03u sz=%u len=%u "
"section=%s type=%s string=%s",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, str);
#else
r_cons_printf ("%03u 0x%08"PFMT64x" 0x%08"
PFMT64x" %3u %3u "
"(%s) %5s %s",
string->ordinal, paddr, vaddr,
string->length, string->size,
section_name, type_string, str);
#endif
if (str == no_dbl_bslash_str) {
R_FREE (str);
}
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't show block list if
just Basic Latin (0x00 - 0x7F) */
break;
}
int *block_ptr = block_list;
r_cons_printf (" blocks=");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *name = r_utf_block_name (*block_ptr);
r_cons_printf ("%s", name? name: "");
}
free (block_list);
}
break;
}
r_cons_printf ("\n");
}
last_processed = iter;
}
R_FREE (b64.string);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
}
if (IS_MODE_SET (mode)) {
r_cons_break_pop ();
}
}
static bool bin_raw_strings(RCore *r, int mode, int va) {
RBinFile *bf = r_bin_cur (r->bin);
bool new_bf = false;
if (bf && strstr (bf->file, "malloc://")) {
//sync bf->buf to search string on it
r_io_read_at (r->io, 0, bf->buf->buf, bf->size);
}
if (!r->file) {
eprintf ("Core file not open\n");
return false;
}
if (!bf) {
bf = R_NEW0 (RBinFile);
if (!bf) {
return false;
}
RIODesc *desc = r_io_desc_get (r->io, r->file->fd);
if (!desc) {
free (bf);
return false;
}
bf->file = strdup (desc->name);
bf->size = r_io_desc_size (desc);
if (bf->size == UT64_MAX) {
free (bf);
return false;
}
bf->buf = r_buf_new_with_io (&r->bin->iob, r->file->fd);
#if 0
bf->buf = r_buf_new ();
if (!bf->buf) {
free (bf);
return false;
}
bf->buf->buf = malloc (bf->size);
if (!bf->buf->buf) {
free (bf->buf);
free (bf);
return false;
}
bf->buf->fd = r->file->fd;
bf->buf->length = bf->size;
r_io_read_at (r->io, 0, bf->buf->buf, bf->size);
#endif
bf->o = NULL;
bf->rbin = r->bin;
new_bf = true;
va = false;
}
RList *l = r_bin_raw_strings (bf, 0);
_print_strings (r, l, mode, va);
if (new_bf) {
r_buf_free (bf->buf);
bf->buf = NULL;
bf->id = -1;
r_bin_file_free (bf);
}
return true;
}
static bool bin_strings(RCore *r, int mode, int va) {
RList *list;
RBinFile *binfile = r_core_bin_cur (r);
RBinPlugin *plugin = r_bin_file_cur_plugin (binfile);
int rawstr = r_config_get_i (r->config, "bin.rawstr");
if (!binfile) {
return false;
}
if (!r_config_get_i (r->config, "bin.strings")) {
return false;
}
if (!plugin) {
return false;
}
if (plugin->info && plugin->name) {
if (strcmp (plugin->name, "any") == 0 && !rawstr) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
}
if (!(list = r_bin_get_strings (r->bin))) {
return false;
}
_print_strings (r, list, mode, va);
return true;
}
static const char* get_compile_time(Sdb *binFileSdb) {
Sdb *info_ns = sdb_ns (binFileSdb, "info", false);
const char *timeDateStamp_string = sdb_const_get (info_ns,
"image_file_header.TimeDateStamp_string", 0);
return timeDateStamp_string;
}
static int is_executable(RBinObject *obj) {
RListIter *it;
RBinSection* sec;
if (obj) {
if (obj->info && obj->info->arch) {
return true;
}
r_list_foreach (obj->sections, it, sec) {
if (R_BIN_SCN_EXECUTABLE & sec->srwx) {
return true;
}
}
}
return false;
}
static void sdb_concat_by_path(Sdb *s, const char *path) {
Sdb *db = sdb_new (0, path, 0);
sdb_merge (s, db);
sdb_close (db);
sdb_free (db);
}
R_API void r_core_anal_type_init(RCore *core) {
Sdb *types = NULL;
const char *anal_arch = NULL, *os = NULL;
char *dbpath;
if (!core || !core->anal) {
return;
}
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
int bits = core->assembler->bits;
types = core->anal->sdb_types;
// make sure they are empty this is initializing
sdb_reset (types);
anal_arch = r_config_get (core->config, "anal.arch");
os = r_config_get (core->config, "asm.os");
// spaguetti ahead
dbpath = sdb_fmt ("%s/"DBSPATH"/types.sdb", dir_prefix);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s.sdb", dir_prefix, anal_arch);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s.sdb", dir_prefix, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%d.sdb", dir_prefix, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%d.sdb", dir_prefix, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%d.sdb", dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%s.sdb", dir_prefix, anal_arch, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%s-%d.sdb", dir_prefix, anal_arch, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
}
static int save_ptr(void *p, const char *k, const char *v) {
Sdb *sdbs[2];
sdbs[0] = ((Sdb**) p)[0];
sdbs[1] = ((Sdb**) p)[1];
if (!strncmp (v, "cc", strlen ("cc") + 1)) {
const char *x = sdb_const_get (sdbs[1], sdb_fmt ("cc.%s.name", k), 0);
char *tmp = sdb_fmt ("%p", x);
sdb_set (sdbs[0], tmp, x, 0);
}
return 1;
}
R_API void r_core_anal_cc_init(RCore *core) {
Sdb *sdbs[2] = {
sdb_new0 (),
core->anal->sdb_cc
};
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
//save pointers and values stored inside them
//to recover from freeing heeps
const char *defaultcc = sdb_const_get (sdbs[1], "default.cc", 0);
sdb_set (sdbs[0], sdb_fmt ("0x%08"PFMT64x, r_num_get (NULL, defaultcc)), defaultcc, 0);
sdb_foreach (core->anal->sdb_cc, save_ptr, sdbs);
sdb_reset ( core->anal->sdb_cc);
const char *anal_arch = r_config_get (core->config, "anal.arch");
int bits = core->anal->bits;
if (bits == 16 && !strcmp (anal_arch, "arm")) {
bits = 32;
}
char *dbpath = sdb_fmt ("%s/"DBSPATH"/cc-%s-%d.sdb", dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (core->anal->sdb_cc, dbpath);
}
//restore all freed CC or replace with new default cc
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
char *ptr = sdb_fmt ("%p", fcn->cc);
const char *cc = sdb_const_get (sdbs[0], ptr, 0);
if (cc) {
fcn->cc = r_anal_cc_to_constant (core->anal, (char *)cc);
}
if (!fcn->cc) {
fcn->cc = r_anal_cc_default (core->anal);
}
fcn->cc = r_str_const (fcn->cc);
}
sdb_close (sdbs[0]);
sdb_free (sdbs[0]);
}
#undef DBSPATH
static int bin_info(RCore *r, int mode) {
int i, j, v;
char str[R_FLAG_NAME_SIZE];
RBinInfo *info = r_bin_get_info (r->bin);
RBinFile *binfile = r_core_bin_cur (r);
RBinObject *obj = r_bin_cur_object (r->bin);
const char *compiled = NULL;
bool havecode;
if (!binfile || !info || !obj) {
if (mode & R_CORE_BIN_JSON) {
r_cons_printf ("{}");
}
return false;
}
havecode = is_executable (obj) | (obj->entries != NULL);
compiled = get_compile_time (binfile->sdb);
if (IS_MODE_SET (mode)) {
r_config_set (r->config, "file.type", info->rclass);
r_config_set (r->config, "cfg.bigendian",
info->big_endian ? "true" : "false");
if (info->rclass && !strcmp (info->rclass, "fs")) {
// r_config_set (r->config, "asm.arch", info->arch);
// r_core_seek (r, 0, 1);
// eprintf ("m /root %s 0", info->arch);
// r_core_cmdf (r, "m /root hfs @ 0", info->arch);
} else {
if (info->lang) {
r_config_set (r->config, "bin.lang", info->lang);
}
r_config_set (r->config, "asm.os", info->os);
if (info->rclass && !strcmp (info->rclass, "pe")) {
r_config_set (r->config, "anal.cpp.abi", "msvc");
} else {
r_config_set (r->config, "anal.cpp.abi", "itanium");
}
r_config_set (r->config, "asm.arch", info->arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "asm.cpu", info->cpu);
}
r_config_set (r->config, "anal.arch", info->arch);
snprintf (str, R_FLAG_NAME_SIZE, "%i", info->bits);
r_config_set (r->config, "asm.bits", str);
r_config_set (r->config, "asm.dwarf",
(R_BIN_DBG_STRIPPED & info->dbg_info) ? "false" : "true");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) r_config_set_i (r->config, "asm.pcalign", v);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("arch %s\n", info->arch);
if (info->cpu && *info->cpu) {
r_cons_printf ("cpu %s\n", info->cpu);
}
r_cons_printf ("bits %d\n", info->bits);
r_cons_printf ("os %s\n", info->os);
r_cons_printf ("endian %s\n", info->big_endian? "big": "little");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
r_cons_printf ("minopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
r_cons_printf ("maxopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("pcalign %d\n", v);
}
} else if (IS_MODE_RAD (mode)) {
if (info->type && !strcmp (info->type, "fs")) {
r_cons_printf ("e file.type=fs\n");
r_cons_printf ("m /root %s 0\n", info->arch);
} else {
r_cons_printf ("e cfg.bigendian=%s\n"
"e asm.bits=%i\n"
"e asm.dwarf=%s\n",
r_str_bool (info->big_endian),
info->bits,
r_str_bool (R_BIN_DBG_STRIPPED &info->dbg_info));
if (info->lang && *info->lang) {
r_cons_printf ("e bin.lang=%s\n", info->lang);
}
if (info->rclass && *info->rclass) {
r_cons_printf ("e file.type=%s\n",
info->rclass);
}
if (info->os) {
r_cons_printf ("e asm.os=%s\n", info->os);
}
if (info->arch) {
r_cons_printf ("e asm.arch=%s\n", info->arch);
}
if (info->cpu && *info->cpu) {
r_cons_printf ("e asm.cpu=%s\n", info->cpu);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) r_cons_printf ("e asm.pcalign=%d\n", v);
}
} else {
// XXX: if type is 'fs' show something different?
char *tmp_buf;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{");
}
pair_str ("arch", info->arch, mode, false);
if (info->cpu && *info->cpu) {
pair_str ("cpu", info->cpu, mode, false);
}
pair_ut64 ("binsz", r_bin_get_size (r->bin), mode, false);
pair_str ("bintype", info->rclass, mode, false);
pair_int ("bits", info->bits, mode, false);
pair_bool ("canary", info->has_canary, mode, false);
pair_str ("class", info->bclass, mode, false);
if (info->actual_checksum) {
/* computed checksum */
pair_str ("cmp.csum", info->actual_checksum, mode, false);
}
pair_str ("compiled", compiled, mode, false);
pair_bool ("crypto", info->has_crypto, mode, false);
pair_str ("dbg_file", info->debug_file_name, mode, false);
pair_str ("endian", info->big_endian ? "big" : "little", mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
tmp_buf = sdb_get (binfile->sdb, "mdmp.flags", 0);
if (tmp_buf) {
pair_str ("flags", tmp_buf, mode, false);
free (tmp_buf);
}
}
pair_bool ("havecode", havecode, mode, false);
if (info->claimed_checksum) {
/* checksum specified in header */
pair_str ("hdr.csum", info->claimed_checksum, mode, false);
}
pair_str ("guid", info->guid, mode, false);
pair_str ("intrp", info->intrp, mode, false);
pair_str ("lang", info->lang, mode, false);
pair_bool ("linenum", R_BIN_DBG_LINENUMS & info->dbg_info, mode, false);
pair_bool ("lsyms", R_BIN_DBG_SYMS & info->dbg_info, mode, false);
pair_str ("machine", info->machine, mode, false);
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
pair_int ("maxopsz", v, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
pair_int ("minopsz", v, mode, false);
}
pair_bool ("nx", info->has_nx, mode, false);
pair_str ("os", info->os, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
pair_bool ("overlay", info->pe_overlay, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
pair_int ("pcalign", v, mode, false);
}
pair_bool ("pic", info->has_pi, mode, false);
pair_bool ("relocs", R_BIN_DBG_RELOCS & info->dbg_info, mode, false);
tmp_buf = sdb_get (obj->kv, "elf.relro", 0);
if (tmp_buf) {
pair_str ("relro", tmp_buf, mode, false);
free (tmp_buf);
}
pair_str ("rpath", info->rpath, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
//this should be moved if added to mach0 (or others)
pair_bool ("signed", info->signature, mode, false);
}
pair_bool ("static", r_bin_is_static (r->bin), mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
v = sdb_num_get (binfile->sdb, "mdmp.streams", 0);
if (v != -1) {
pair_int ("streams", v, mode, false);
}
}
pair_bool ("stripped", R_BIN_DBG_STRIPPED & info->dbg_info, mode, false);
pair_str ("subsys", info->subsystem, mode, false);
pair_bool ("va", info->has_va, mode, true);
if (IS_MODE_JSON (mode)) {
r_cons_printf (",\"checksums\":{");
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
int len = r_hash_calculate (rh, hash, (const ut8*)
binfile->buf->buf+h->from, h->to);
if (len < 1) {
eprintf ("Invaild checksum length\n");
}
r_hash_free (rh);
r_cons_printf ("%s\"%s\":{\"hex\":\"", i?",": "", h->type);
// r_cons_printf ("%s\t%d-%dc\t", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_printf ("\"}");
}
r_cons_printf ("}");
} else {
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
int len = r_hash_calculate (rh, hash, (const ut8*)
binfile->buf->buf+h->from, h->to);
if (len < 1) {
eprintf ("Invaild wtf\n");
}
r_hash_free (rh);
r_cons_printf ("%s %d-%dc ", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_newline ();
}
}
if (IS_MODE_JSON (mode)) r_cons_printf ("}");
}
r_core_anal_type_init (r);
r_core_anal_cc_init (r);
return true;
}
static int bin_dwarf(RCore *core, int mode) {
RBinDwarfRow *row;
RListIter *iter;
RList *list = NULL;
if (!r_config_get_i (core->config, "bin.dbginfo")) {
return false;
}
RBinFile *binfile = r_core_bin_cur (core);
RBinPlugin * plugin = r_bin_file_cur_plugin (binfile);
if (!binfile) {
return false;
}
if (plugin && plugin->lines) {
list = plugin->lines (binfile);
} else if (core->bin) {
// TODO: complete and speed-up support for dwarf
RBinDwarfDebugAbbrev *da = NULL;
da = r_bin_dwarf_parse_abbrev (core->bin, mode);
r_bin_dwarf_parse_info (da, core->bin, mode);
r_bin_dwarf_parse_aranges (core->bin, mode);
list = r_bin_dwarf_parse_line (core->bin, mode);
r_bin_dwarf_free_debug_abbrev (da);
free (da);
}
if (!list) {
return false;
}
r_cons_break_push (NULL, NULL);
/* cache file:line contents */
const char *lastFile = NULL;
int *lastFileLines = NULL;
char *lastFileContents = NULL;
int lastFileLinesCount = 0;
/* ugly dupe for speedup */
const char *lastFile2 = NULL;
int *lastFileLines2 = NULL;
char *lastFileContents2 = NULL;
int lastFileLinesCount2 = 0;
const char *lf = NULL;
int *lfl = NULL;
char *lfc = NULL;
int lflc = 0;
//TODO we should need to store all this in sdb, or do a filecontentscache in libr/util
//XXX this whole thing has leaks
r_list_foreach (list, iter, row) {
if (r_cons_is_breaked ()) {
break;
}
if (mode) {
// TODO: use 'Cl' instead of CC
const char *path = row->file;
if (!lastFile || strcmp (path, lastFile)) {
if (lastFile && lastFile2 && !strcmp (path, lastFile2)) {
lf = lastFile;
lfl = lastFileLines;
lfc = lastFileContents;
lflc = lastFileLinesCount;
lastFile = lastFile2;
lastFileLines = lastFileLines2;
lastFileContents = lastFileContents2;
lastFileLinesCount = lastFileLinesCount2;
lastFile2 = lf;
lastFileLines2 = lfl;
lastFileContents2 = lfc;
lastFileLinesCount2 = lflc;
} else {
lastFile2 = lastFile;
lastFileLines2 = lastFileLines;
lastFileContents2 = lastFileContents;
lastFileLinesCount2 = lastFileLinesCount;
lastFile = path;
lastFileContents = r_file_slurp (path, NULL);
if (lastFileContents) {
lastFileLines = r_str_split_lines (lastFileContents, &lastFileLinesCount);
}
}
}
char *line = NULL;
//r_file_slurp_line (path, row->line - 1, 0);
if (lastFileLines && lastFileContents) {
int nl = row->line - 1;
if (nl >= 0 && nl < lastFileLinesCount) {
line = strdup (lastFileContents + lastFileLines[nl]);
}
} else {
line = NULL;
}
if (line) {
r_str_filter (line, strlen (line));
line = r_str_replace (line, "\"", "\\\"", 1);
line = r_str_replace (line, "\\\\", "\\", 1);
}
bool chopPath = !r_config_get_i (core->config, "dir.dwarf.abspath");
char *file = strdup (row->file);
if (chopPath) {
const char *slash = r_str_lchr (file, '/');
if (slash) {
memmove (file, slash + 1, strlen (slash));
}
}
// TODO: implement internal : if ((mode & R_CORE_BIN_SET))
if ((mode & R_CORE_BIN_SET)) {
// TODO: use CL here.. but its not necessary.. so better not do anything imho
// r_core_cmdf (core, "CL %s:%d 0x%08"PFMT64x, file, (int)row->line, row->address);
#if 0
char *cmt = r_str_newf ("%s:%d %s", file, (int)row->line, line? line: "");
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, row->address, cmt);
free (cmt);
#endif
} else {
r_cons_printf ("CL %s:%d 0x%08" PFMT64x "\n",
file, (int)row->line,
row->address);
r_cons_printf ("\"CC %s:%d %s\"@0x%" PFMT64x
"\n",
file, row->line,
line ? line : "", row->address);
}
free (file);
free (line);
} else {
r_cons_printf ("0x%08" PFMT64x "\t%s\t%d\n",
row->address, row->file, row->line);
}
}
r_cons_break_pop ();
R_FREE (lastFileContents);
R_FREE (lastFileContents2);
// this list is owned by rbin, not us, we shouldnt free it
// r_list_free (list);
free (lastFileLines);
return true;
}
R_API int r_core_pdb_info(RCore *core, const char *file, ut64 baddr, int mode) {
R_PDB pdb = R_EMPTY;
pdb.cb_printf = r_cons_printf;
if (!init_pdb_parser (&pdb, file)) {
return false;
}
if (!pdb.pdb_parse (&pdb)) {
eprintf ("pdb was not parsed\n");
pdb.finish_pdb_parse (&pdb);
return false;
}
if (mode == R_CORE_BIN_JSON) {
r_cons_printf("[");
}
switch (mode) {
case R_CORE_BIN_SET:
mode = 's';
r_core_cmd0 (core, ".iP*");
return true;
case R_CORE_BIN_JSON:
mode = 'j';
break;
case '*':
case 1:
mode = 'r';
break;
default:
mode = 'd'; // default
break;
}
pdb.print_types (&pdb, mode);
if (mode == 'j') {
r_cons_printf (",");
}
pdb.print_gvars (&pdb, baddr, mode);
if (mode == 'j') {
r_cons_printf ("]");
}
pdb.finish_pdb_parse (&pdb);
return true;
}
static int bin_pdb(RCore *core, int mode) {
ut64 baddr = r_bin_get_baddr (core->bin);
return r_core_pdb_info (core, core->bin->file, baddr, mode);
}
static int bin_main(RCore *r, int mode, int va) {
RBinAddr *binmain = r_bin_get_sym (r->bin, R_BIN_SYM_MAIN);
ut64 addr;
if (!binmain) {
return false;
}
addr = va ? r_bin_a2b (r->bin, binmain->vaddr) : binmain->paddr;
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
r_flag_set (r->flags, "main", addr, r->blocksize);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("%"PFMT64d, addr);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
r_cons_printf ("f main @ 0x%08"PFMT64x"\n", addr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"vaddr\":%" PFMT64d
",\"paddr\":%" PFMT64d "}", addr, binmain->paddr);
} else {
r_cons_printf ("[Main]\n");
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x"\n",
addr, binmain->paddr);
}
return true;
}
static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
if (r_list_length (entries) > 1024) {
eprintf ("Too many entrypoints (%d)\n", r_list_length (entries));
return false;
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (mode != R_CORE_BIN_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
if (r->io->va && entry->paddr == entry->vaddr) {
RIOMap *map = r_io_map_get (r->io, entry->vaddr);
if (map) {
paddr = entry->vaddr - map->itv.addr + map->delta;
}
}
}
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry%i.preinit", i);
} else {
name = r_str_newf ("entry%i", i);
}
r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at);
r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr);
r_cons_printf ("s %s\n", name);
free (name);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
static const char *bin_reloc_type_name(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return reloc->additive ? "ADD_" #T : "SET_" #T
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return "UNKNOWN";
#undef CASE
}
static ut8 bin_reloc_size(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return T / 8
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return 0;
#undef CASE
}
static char *resolveModuleOrdinal(Sdb *sdb, const char *module, int ordinal) {
Sdb *db = sdb;
char *foo = sdb_get (db, sdb_fmt ("%d", ordinal), 0);
return (foo && *foo) ? foo : NULL;
}
static char *get_reloc_name(RBinReloc *reloc, ut64 addr) {
char *reloc_name = NULL;
if (reloc->import && reloc->import->name) {
reloc_name = sdb_fmt ("reloc.%s_%d", reloc->import->name,
(int)(addr & 0xff));
if (!reloc_name) {
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->symbol && reloc->symbol->name) {
reloc_name = sdb_fmt ("reloc.%s_%d", reloc->symbol->name, (int)(addr & 0xff));
if (!reloc_name) {
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->is_ifunc) {
// addend is the function pointer for the resolving ifunc
reloc_name = sdb_fmt ("reloc.ifunc_%"PFMT64x, reloc->addend);
} else {
// TODO(eddyb) implement constant relocs.
}
return reloc_name;
}
static void set_bin_relocs(RCore *r, RBinReloc *reloc, ut64 addr, Sdb **db, char **sdb_module) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
const char *lang = r_config_get (r->config, "bin.lang");
char *reloc_name, *demname = NULL;
bool is_pe = true;
int is_sandbox = r_sandbox_enable (0);
if (reloc->import && reloc->import->name[0]) {
char str[R_FLAG_NAME_SIZE];
RFlagItem *fi;
if (is_pe && !is_sandbox && strstr (reloc->import->name, "Ordinal")) {
const char *TOKEN = ".dll_Ordinal_";
char *module = strdup (reloc->import->name);
char *import = strstr (module, TOKEN);
r_str_case (module, false);
if (import) {
char *filename = NULL;
int ordinal;
*import = 0;
import += strlen (TOKEN);
ordinal = atoi (import);
if (!*sdb_module || strcmp (module, *sdb_module)) {
sdb_free (*db);
*db = NULL;
free (*sdb_module);
*sdb_module = strdup (module);
/* always lowercase */
filename = sdb_fmt ("%s.sdb", module);
r_str_case (filename, false);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
} else {
// XXX. we have dir.prefix, windows shouldnt work different
filename = sdb_fmt ("%s/share/radare2/" R2_VERSION"/format/dll/%s.sdb", r_config_get (r->config, "dir.prefix"), module);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
#if __WINDOWS__
} else {
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, module);
} else {
filename = sdb_fmt ("share/radare2/"R2_VERSION"/format/dll/%s.sdb", module);
}
#else
filename = sdb_fmt ("%s/share/radare2/" R2_VERSION"/format/dll/%s.sdb", r_config_get (r->config, "dir.prefix"), module);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
}
#endif
}
}
}
if (*db) {
// ordinal-1 because we enumerate starting at 0
char *symname = resolveModuleOrdinal (*db, module, ordinal - 1); // uses sdb_get
if (symname) {
if (r->bin->prefix) {
reloc->import->name = r_str_newf
("%s.%s.%s", r->bin->prefix, module, symname);
} else {
reloc->import->name = r_str_newf
("%s.%s", module, symname);
}
R_FREE (symname);
}
}
}
free (module);
r_anal_hint_set_size (r->anal, reloc->vaddr, 4);
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr+4, NULL);
}
reloc_name = reloc->import->name;
if (r->bin->prefix) {
snprintf (str, R_FLAG_NAME_SIZE, "%s.reloc.%s", r->bin->prefix, reloc_name);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s", reloc_name);
}
if (bin_demangle) {
demname = r_bin_demangle (r->bin->cur, lang, str, addr);
}
r_name_filter (str, 0);
fi = r_flag_set (r->flags, str, addr, bin_reloc_size (reloc));
if (demname) {
char *realname;
if (r->bin->prefix) {
realname = sdb_fmt ("%s.reloc.%s", r->bin->prefix, demname);
} else {
realname = sdb_fmt ("reloc.%s", demname);
}
r_flag_item_set_realname (fi, realname);
}
} else {
char *reloc_name = get_reloc_name (reloc, addr);
r_flag_set (r->flags, reloc_name, addr, bin_reloc_size (reloc));
}
}
/* Define new data at relocation address if it's not in an executable section */
static void add_metadata(RCore *r, RBinReloc *reloc, ut64 addr, int mode) {
RBinFile * binfile = r->bin->cur;
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
RIOSection *section;
int cdsz;
cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (cdsz == 0) {
return;
}
section = r_io_section_vget (r->io, addr);
if (!section || section->flags & R_IO_EXEC) {
return;
}
if (IS_MODE_SET(mode)) {
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr + cdsz, NULL);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f Cd %d @ 0x%08" PFMT64x "\n", cdsz, addr);
}
}
static bool is_section_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
if (!s || *s->name) {
return false;
}
return (s->type && !strcmp (s->type, "SECTION"));
}
static bool is_section_reloc(RBinReloc *r) {
return is_section_symbol (r->symbol);
}
static bool is_file_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
return (s && s->type && !strcmp (s->type, "FILE"));
}
static bool is_file_reloc(RBinReloc *r) {
return is_file_symbol (r->symbol);
}
static int bin_relocs(RCore *r, int mode, int va) {
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
RList *relocs;
RListIter *iter;
RBinReloc *reloc = NULL;
Sdb *db = NULL;
char *sdb_module = NULL;
int i = 0;
va = VA_TRUE; // XXX relocs always vaddr?
//this has been created for reloc object files
relocs = r_bin_patch_relocs (r->bin);
if (!relocs) {
relocs = r_bin_get_relocs (r->bin);
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs relocs");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Relocations]");
} else if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "relocs");
}
r_list_foreach (relocs, iter, reloc) {
ut64 addr = rva (r->bin, reloc->paddr, reloc->vaddr, va);
if (IS_MODE_SET (mode) && (is_section_reloc (reloc) || is_file_reloc (reloc))) {
/*
* Skip section reloc because they will have their own flag.
* Skip also file reloc because not useful for now.
*/
} else if (IS_MODE_SET (mode)) {
set_bin_relocs (r, reloc, addr, &db, &sdb_module);
add_metadata (r, reloc, addr, mode);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" %s\n", addr, reloc->import ? reloc->import->name : "");
} else if (IS_MODE_RAD (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: (reloc->symbol ? strdup (reloc->symbol->name) : NULL);
if (name && bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr);
if (mn) {
free (name);
name = mn;
}
}
if (name) {
r_cons_printf ("f %s%s%s @ 0x%08"PFMT64x"\n",
r->bin->prefix ? r->bin->prefix : "reloc.",
r->bin->prefix ? "." : "", name, addr);
add_metadata (r, reloc, addr, mode);
free (name);
}
} else if (IS_MODE_JSON (mode)) {
if (iter->p) {
r_cons_printf (",{\"name\":");
} else {
r_cons_printf ("{\"name\":");
}
// take care with very long symbol names! do not use sdb_fmt or similar
if (reloc->import) {
r_cons_printf ("\"%s\"", reloc->import->name);
} else if (reloc->symbol) {
r_cons_printf ("\"%s\"", reloc->symbol->name);
} else {
r_cons_printf ("null");
}
r_cons_printf (","
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d","
"\"is_ifunc\":%s}",
bin_reloc_type_name (reloc),
reloc->vaddr, reloc->paddr,
r_str_bool (reloc->is_ifunc));
} else if (IS_MODE_NORMAL (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: reloc->symbol
? strdup (reloc->symbol->name)
: strdup ("null");
if (bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr);
if (mn && *mn) {
free (name);
name = mn;
}
}
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" type=%s",
addr, reloc->paddr, bin_reloc_type_name (reloc));
if (reloc->import && reloc->import->name[0]) {
r_cons_printf (" %s", name);
} else if (reloc->symbol && name && name[0]) {
r_cons_printf (" %s", name);
}
free (name);
if (reloc->addend) {
if (reloc->import && reloc->addend > 0) {
r_cons_printf (" +");
}
if (reloc->addend < 0) {
r_cons_printf (" - 0x%08"PFMT64x, -reloc->addend);
} else {
r_cons_printf (" 0x%08"PFMT64x, reloc->addend);
}
}
if (reloc->is_ifunc) {
r_cons_print (" (ifunc)");
}
r_cons_newline ();
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i relocations\n", i);
}
R_FREE (sdb_module);
sdb_free (db);
db = NULL;
return relocs != NULL;
}
#define MYDB 1
/* this is a hacky workaround that needs proper refactoring in Rbin to use Sdb */
#if MYDB
static Sdb *mydb = NULL;
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol, *res = NULL;
RListIter *iter;
if (mydb && symbols && symbols != osymbols) {
sdb_free (mydb);
mydb = NULL;
osymbols = symbols;
}
if (mydb) {
if (name) {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("%x", sdb_hash (name)), NULL);
} else {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("0x"PFMT64x, addr), NULL);
}
} else {
mydb = sdb_new0 ();
r_list_foreach (symbols, iter, symbol) {
/* ${name}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("%x", sdb_hash (symbol->name)), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
/* 0x${vaddr}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("0x"PFMT64x, symbol->vaddr), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
if (name) {
if (!res && !strcmp (symbol->name, name)) {
res = symbol;
}
} else {
if (symbol->vaddr == addr) {
res = symbol;
}
}
}
osymbols = symbols;
}
return res;
}
#else
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol;
RListIter *iter;
// XXX this is slow, we should use a hashtable here
r_list_foreach (symbols, iter, symbol) {
if (name) {
if (!strcmp (symbol->name, name))
return symbol;
} else {
if (symbol->vaddr == addr) {
return symbol;
}
}
}
return NULL;
}
#endif
/* XXX: This is a hack to get PLT references in rabin2 -i */
/* imp. is a prefix that can be rewritten by the symbol table */
static ut64 impaddr(RBin *bin, int va, const char *name) {
RList *symbols;
if (!name || !*name) {
return false;
}
if (!(symbols = r_bin_get_symbols (bin))) {
return false;
}
char *impname = r_str_newf ("imp.%s", name);
RBinSymbol *s = get_symbol (bin, symbols, impname, 0LL);
// maybe ut64_MAX to indicate import not found?
ut64 addr = s? (va? r_bin_get_vaddr (bin, s->paddr, s->vaddr): s->paddr): 0LL;
free (impname);
return addr;
}
static int bin_imports(RCore *r, int mode, int va, const char *name) {
RBinInfo *info = r_bin_get_info (r->bin);
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
RBinImport *import;
RListIter *iter;
bool lit = info ? info->has_lit: false;
char *str;
int i = 0;
RList *imports = r_bin_get_imports (r->bin);
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs imports");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Imports]");
}
r_list_foreach (imports, iter, import) {
if (name && strcmp (import->name, name)) {
continue;
}
char *symname = strdup (import->name);
ut64 addr = lit ? impaddr (r->bin, va, symname): 0;
if (bin_demangle) {
char *dname = r_bin_demangle (r->bin->cur, NULL, symname, addr);
if (dname) {
free (symname);
symname = r_str_newf ("sym.imp.%s", dname);
free (dname);
}
}
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, symname);
free (symname);
symname = prname;
}
if (IS_MODE_SET (mode)) {
// TODO(eddyb) symbols that are imports.
// Add a dword/qword for PE imports
if (strstr (symname, ".dll_") && cdsz) {
r_meta_add (r->anal, R_META_TYPE_DATA, addr, addr + cdsz, NULL);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_println (symname);
} else if (IS_MODE_JSON (mode)) {
str = r_str_utf16_encode (symname, -1);
str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"type\":\"%s\",",
iter->p ? "," : "",
import->ordinal,
import->bind,
import->type);
if (import->classname && import->classname[0]) {
r_cons_printf ("\"classname\":\"%s\","
"\"descriptor\":\"%s\",",
import->classname,
import->descriptor);
}
r_cons_printf ("\"name\":\"%s\",\"plt\":%"PFMT64d"}",
str, addr);
free (str);
} else if (IS_MODE_RAD (mode)) {
// TODO(eddyb) symbols that are imports.
} else {
const char *bind = r_str_get (import->bind);
const char *type = r_str_get (import->type);
#if 0
r_cons_printf ("ordinal=%03d plt=0x%08"PFMT64x" bind=%s type=%s",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf (" classname=%s", import->classname);
}
r_cons_printf (" name=%s", symname);
if (import->descriptor && import->descriptor[0]) {
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#else
r_cons_printf ("%4d 0x%08"PFMT64x" %7s %7s ",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf ("%s.", import->classname);
}
r_cons_printf ("%s", symname);
if (import->descriptor && import->descriptor[0]) {
// Uh?
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#endif
}
R_FREE (symname);
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
// r_cons_printf ("# %i imports\n", i);
}
#if MYDB
// NOTE: if we comment out this, it will leak.. but it will be faster
// because it will keep the cache across multiple RBin calls
osymbols = NULL;
sdb_free (mydb);
mydb = NULL;
#endif
return true;
}
static const char *getPrefixFor(const char *s) {
if (s) {
if (!strcmp (s, "NOTYPE")) {
return "loc";
}
if (!strcmp (s, "OBJECT")) {
return "obj";
}
}
return "sym";
}
typedef struct {
const char *pfx; // prefix for flags
char *name; // raw symbol name
char *nameflag; // flag name for symbol
char *demname; // demangled raw symbol name
char *demflag; // flag name for demangled symbol
char *classname; // classname
char *classflag; // flag for classname
char *methname; // methods [class]::[method]
char *methflag; // methods flag sym.[class].[method]
} SymName;
static void snInit(RCore *r, SymName *sn, RBinSymbol *sym, const char *lang) {
#define MAXFLAG_LEN 128
int bin_demangle = lang != NULL;
const char *pfx;
if (!r || !sym || !sym->name) return;
pfx = getPrefixFor (sym->type);
sn->name = strdup (sym->name);
if (sym->dup_count) {
sn->nameflag = r_str_newf ("%s.%s_%d", pfx, sym->name, sym->dup_count);
} else {
sn->nameflag = r_str_newf ("%s.%s", pfx, sym->name);
}
r_name_filter (sn->nameflag, MAXFLAG_LEN);
if (sym->classname && sym->classname[0]) {
sn->classname = strdup (sym->classname);
sn->classflag = r_str_newf ("sym.%s.%s", sn->classname, sn->name);
r_name_filter (sn->classflag, MAXFLAG_LEN);
const char *name = sym->dname? sym->dname: sym->name;
sn->methname = r_str_newf ("%s::%s", sn->classname, name);
sn->methflag = r_str_newf ("sym.%s.%s", sn->classname, name);
r_name_filter (sn->methflag, strlen (sn->methflag));
} else {
sn->classname = NULL;
sn->classflag = NULL;
sn->methname = NULL;
sn->methflag = NULL;
}
sn->demname = NULL;
sn->demflag = NULL;
if (bin_demangle && sym->paddr) {
sn->demname = r_bin_demangle (r->bin->cur, lang, sn->name, sym->vaddr);
if (sn->demname) {
sn->demflag = r_str_newf ("%s.%s", pfx, sn->demname);
r_name_filter (sn->demflag, -1);
}
}
}
static void snFini(SymName *sn) {
R_FREE (sn->name);
R_FREE (sn->nameflag);
R_FREE (sn->demname);
R_FREE (sn->demflag);
R_FREE (sn->classname);
R_FREE (sn->classflag);
R_FREE (sn->methname);
R_FREE (sn->methflag);
}
static bool isAnExport(RBinSymbol *s) {
/* workaround for some bin plugs */
if (!strncmp (s->name, "imp.", 4)) {
return false;
}
return (s->bind && !strcmp (s->bind, "GLOBAL"));
}
static int bin_symbols_internal(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
RList *symbols;
const char *lang;
bool firstexp = true;
bool printHere = false;
int i = 0, is_arm, lastfs = 's';
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
if (args && *args == '.') {
printHere = true;
}
is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
symbols = r_bin_get_symbols (r->bin);
r_space_set (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Symbols]\n");
}
}
r_list_foreach (symbols, iter, symbol) {
ut64 addr = rva (r->bin, symbol->paddr, symbol->vaddr, va);
int len = symbol->size ? symbol->size : 32;
SymName sn;
if (exponly && !isAnExport (symbol)) {
continue;
}
if (name && strcmp (symbol->name, name)) {
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
continue;
}
if ((printHere && !is_in_range (r->offset, symbol->paddr, len))
&& (printHere && !is_in_range (r->offset, addr, len))) {
continue;
}
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {
/*
* Skip section symbols because they will have their own flag.
* Skip also file symbols because not useful for now.
*/
} else if (IS_MODE_SET (mode)) {
if (is_arm && info->bits < 33) { // 16 or 32
int force_bits = 0;
if (symbol->paddr & 1 || symbol->bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && symbol->bits == 32) {
force_bits = 32;
} else if (!(symbol->paddr & 1) && symbol->bits == 32) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (r->anal, addr, force_bits);
}
}
if (!strncmp (symbol->name, "imp.", 4)) {
if (lastfs != 'i') {
r_flag_space_set (r->flags, "imports");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
r_flag_space_set (r->flags, "symbols");
}
lastfs = 's';
}
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = NULL;
char *comment = NULL;
fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname;
prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
comment = fi->comment ? strdup (fi->comment) : NULL;
r_flag_unset (r->flags, fi);
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *fn, *n;
RFlagItem *fi;
n = sn.demname ? sn.demname : sn.name;
fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_utf16_encode (symbol->name, -1);
// str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""),
str,
sn.demname? sn.demname: "",
sn.nameflag,
symbol->ordinal,
symbol->bind,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: symbol->name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: symbol->name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
RBinFile *binfile;
RBinPlugin *plugin;
char *name = strdup (sn.demname? sn.demname: symbol->name);
r_name_filter (name, -1);
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i')
r_cons_printf ("fs imports\n");
lastfs = 'i';
} else {
if (lastfs != 's') {
r_cons_printf ("fs %s\n",
exponly? "exports": "symbols");
}
lastfs = 's';
}
if (r->bin->prefix) {
if (symbol->dup_count) {
r_cons_printf ("f %s.sym.%s_%d %u 0x%08"PFMT64x"\n",
r->bin->prefix, name, symbol->dup_count, symbol->size, addr);
} else {
r_cons_printf ("f %s.sym.%s %u 0x%08"PFMT64x"\n",
r->bin->prefix, name, symbol->size, addr);
}
} else {
if (symbol->dup_count) {
r_cons_printf ("f sym.%s_%d %u 0x%08"PFMT64x"\n",
name, symbol->dup_count, symbol->size, addr);
} else {
r_cons_printf ("f sym.%s %u 0x%08"PFMT64x"\n",
name, symbol->size, addr);
}
}
binfile = r_core_bin_cur (r);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (!strncmp (plugin->name, "pe", 2)) {
char *p, *module = strdup (symbol->name);
p = strstr (module, ".dll_");
if (p) {
const char *symname = p + 5;
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("k bin/pe/%s/%d=%s.%s\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("k bin/pe/%s/%d=%s\n",
module, symbol->ordinal, symname);
}
}
free (module);
}
}
} else {
const char *bind = r_str_get (symbol->bind);
const char *type = r_str_get (symbol->type);
const char *name = r_str_get (sn.demname? sn.demname: symbol->name);
// const char *fwd = r_str_get (symbol->forwarder);
r_cons_printf ("%03u 0x%08"PFMT64x" 0x%08"PFMT64x" "
"%6s %6s %4d %s\n",
symbol->ordinal,
symbol->paddr, addr, bind, type,
symbol->size, name);
// r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" ord=%03u "
// "fwd=%s sz=%u bind=%s type=%s name=%s\n",
// addr, symbol->paddr, symbol->ordinal, fwd,
// symbol->size, bind, type, name);
}
snFini (&sn);
i++;
if (exponly && firstexp) {
firstexp = false;
}
if (printHere) {
break;
}
}
//handle thumb and arm for entry point since they are not present in symbols
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
if (info->bits < 33) { // 16 or 32
int force_bits = 0;
ut64 addr = rva (r->bin, entry->paddr, entry->vaddr, va);
if (entry->paddr & 1 || entry->bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && entry->bits == 32) {
force_bits = 32;
} else if (!(entry->paddr & 1)) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (r->anal, addr, force_bits);
}
}
}
}
}
if (IS_MODE_JSON (mode) && !printHere) r_cons_printf ("]");
#if 0
if (IS_MODE_NORMAL (mode) && !at) {
r_cons_printf ("\n%i %s\n", i, exponly ? "exports" : "symbols");
}
#endif
r_space_set (&r->anal->meta_spaces, NULL);
return true;
}
static int bin_exports(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *args) {
return bin_symbols_internal (r, mode, laddr, va, at, name, true, args);
}
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *args) {
return bin_symbols_internal (r, mode, laddr, va, at, name, false, args);
}
static char *build_hash_string(int mode, const char *chksum, ut8 *data, ut32 datalen) {
char *chkstr = NULL, *aux, *ret = NULL;
const char *ptr = chksum;
char tmp[128];
int i;
do {
for (i = 0; *ptr && *ptr != ',' && i < sizeof (tmp) -1; i++) {
tmp[i] = *ptr++;
}
tmp[i] = '\0';
r_str_trim_head_tail (tmp);
chkstr = r_hash_to_string (NULL, tmp, data, datalen);
if (!chkstr) {
if (*ptr && *ptr == ',') {
ptr++;
}
continue;
}
if (IS_MODE_SIMPLE (mode)) {
aux = r_str_newf ("%s ", chkstr);
} else if (IS_MODE_JSON (mode)) {
aux = r_str_newf ("\"%s\":\"%s\",", tmp, chkstr);
} else {
aux = r_str_newf ("%s=%s ", tmp, chkstr);
}
ret = r_str_append (ret, aux);
free (chkstr);
free (aux);
if (*ptr && *ptr == ',') ptr++;
} while (*ptr);
return ret;
}
static int bin_sections(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *chksum) {
char *str = NULL;
RBinSection *section;
RBinInfo *info = NULL;
RList *sections;
RListIter *iter;
int i = 0;
int fd = -1;
bool printHere = false;
sections = r_bin_get_sections (r->bin);
bool inDebugger = r_config_get_i (r->config, "cfg.debug");
SdbHash *dup_chk_ht = ht_new (NULL, NULL, NULL);
bool ret = false;
if (!dup_chk_ht) {
return false;
}
if (chksum && *chksum == '.') {
printHere = true;
}
if (IS_MODE_JSON (mode) && !printHere) r_cons_printf ("[");
else if (IS_MODE_RAD (mode) && !at) r_cons_printf ("fs sections\n");
else if (IS_MODE_NORMAL (mode) && !at && !printHere) r_cons_printf ("[Sections]\n");
else if (IS_MODE_NORMAL (mode) && printHere) r_cons_printf("Current section\n");
else if (IS_MODE_SET (mode)) {
fd = r_core_file_cur_fd (r);
r_flag_space_set (r->flags, "sections");
}
r_list_foreach (sections, iter, section) {
char perms[] = "----";
int va_sect = va;
ut64 addr;
if (va && !(section->srwx & R_BIN_SCN_READABLE)) {
va_sect = VA_NOREBASE;
}
addr = rva (r->bin, section->paddr, section->vaddr, va_sect);
if (name && strcmp (section->name, name)) {
continue;
}
if ((printHere && !(section->paddr <= r->offset && r->offset < (section->paddr + section->size)))
&& (printHere && !(addr <= r->offset && r->offset < (addr + section->size)))) {
continue;
}
r_name_filter (section->name, sizeof (section->name));
if (at && (!section->size || !is_in_range (at, addr, section->size))) {
continue;
}
if (section->srwx & R_BIN_SCN_SHAREABLE) perms[0] = 's';
if (section->srwx & R_BIN_SCN_READABLE) perms[1] = 'r';
if (section->srwx & R_BIN_SCN_WRITABLE) perms[2] = 'w';
if (section->srwx & R_BIN_SCN_EXECUTABLE) perms[3] = 'x';
if (IS_MODE_SET (mode)) {
#if LOAD_BSS_MALLOC
if (!strcmp (section->name, ".bss")) {
// check if there's already a file opened there
int loaded = 0;
RListIter *iter;
RIOMap *m;
r_list_foreach (r->io->maps, iter, m) {
if (m->from == addr) {
loaded = 1;
}
}
if (!loaded && !inDebugger) {
r_core_cmdf (r, "on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
}
}
#endif
r_name_filter (section->name, 128);
if (section->format) {
// This is damn slow if section vsize is HUGE
if (section->vsize < 1024 * 1024 * 2) {
r_core_cmdf (r, "%s @ 0x%"PFMT64x, section->format, section->vaddr);
}
}
if (r->bin->prefix) {
str = r_str_newf ("%s.section.%s", r->bin->prefix, section->name);
} else {
str = r_str_newf ("section.%s", section->name);
}
r_flag_set (r->flags, str, addr, section->size);
R_FREE (str);
if (r->bin->prefix) {
str = r_str_newf ("%s.section_end.%s", r->bin->prefix, section->name);
} else {
str = r_str_newf ("section_end.%s", section->name);
}
r_flag_set (r->flags, str, addr + section->vsize, 0);
R_FREE (str);
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (info) {
if (!arch) {
arch = info->arch;
}
if (!bits) {
bits = info->bits;
}
}
//r_io_section_set_archbits (r->io, addr, arch, bits);
}
char *pfx = r->bin->prefix;
str = r_str_newf ("[%02d] %s section size %" PFMT64d" named %s%s%s",
i, perms, section->size,
pfx? pfx: "", pfx? ".": "", section->name);
r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, addr, str);
R_FREE (str);
if (section->add) {
str = r_str_newf ("%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT32u".%s.%"PFMT32u".%d",
section->paddr, addr, section->size, section->vsize, section->srwx, section->name, r->bin->cur->id, fd);
if (!ht_find (dup_chk_ht, str, NULL) && r_io_section_add (r->io, section->paddr, addr,
section->size, section->vsize,
section->srwx, section->name,
r->bin->cur->id, fd)) {
ht_insert (dup_chk_ht, str, NULL);
}
R_FREE (str);
}
} else if (IS_MODE_SIMPLE (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("0x%"PFMT64x" 0x%"PFMT64x" %s %s%s%s\n",
addr, addr + section->size,
perms,
hashstr ? hashstr : "", hashstr ? " " : "",
section->name
);
free (hashstr);
} else if (IS_MODE_JSON (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("%s{\"name\":\"%s\","
"\"size\":%"PFMT64d","
"\"vsize\":%"PFMT64d","
"\"flags\":\"%s\","
"%s"
"\"paddr\":%"PFMT64d","
"\"vaddr\":%"PFMT64d"}",
(iter->p && !printHere)?",":"",
section->name,
section->size,
section->vsize,
perms,
hashstr ? hashstr : "",
section->paddr,
addr);
free (hashstr);
} else if (IS_MODE_RAD (mode)) {
if (!strcmp (section->name, ".bss") && !inDebugger) {
#if LOAD_BSS_MALLOC
r_cons_printf ("on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
#endif
}
if (r->bin->prefix) {
r_cons_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" %s.%s %d\n",
section->paddr, addr, section->size, section->vsize,
r->bin->prefix, section->name, (int)section->srwx);
} else {
r_cons_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" %s %d\n",
section->paddr, addr, section->size, section->vsize,
section->name, (int)section->srwx);
}
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (info) {
if (!arch) arch = info->arch;
if (!bits) bits = info->bits;
}
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
r_cons_printf ("Sa %s %d @ 0x%08"
PFMT64x"\n", arch, bits, addr);
}
if (r->bin->prefix) {
r_cons_printf ("f %s.section.%s %"PFMT64d" 0x%08"PFMT64x"\n",
r->bin->prefix, section->name, section->size, addr);
r_cons_printf ("f %s.section_end.%s 1 0x%08"PFMT64x"\n",
r->bin->prefix, section->name, addr + section->vsize);
r_cons_printf ("CC section %i va=0x%08"PFMT64x" pa=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"rwx=%s %s.%s @ 0x%08"PFMT64x"\n",
i, addr, section->paddr, section->size, section->vsize,
perms, r->bin->prefix, section->name, addr);
} else {
r_cons_printf ("f section.%s %"PFMT64d" 0x%08"PFMT64x"\n",
section->name, section->size, addr);
r_cons_printf ("f section_end.%s 1 0x%08"PFMT64x"\n",
section->name, addr + section->vsize);
r_cons_printf ("CC section %i va=0x%08"PFMT64x" pa=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"rwx=%s %s @ 0x%08"PFMT64x"\n",
i, addr, section->paddr, section->size, section->vsize,
perms, section->name, addr);
}
} else {
char *hashstr = NULL, str[128];
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
// VA READ IS BROKEN?
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (!arch && info) {
arch = info->arch;
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
}
if (!bits) {
bits = info? info->bits: R_SYS_BITS;
}
snprintf (str, sizeof (str), "arch=%s bits=%d ",
r_str_get2 (arch), bits);
} else {
str[0] = 0;
}
if (r->bin->prefix) {
#if 0
r_cons_printf ("idx=%02i vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"perm=%s %s%sname=%s.%s\n",
i, addr, section->paddr, section->size, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
#endif
// r_cons_printf ("%02i 0x%08"PFMT64x" %10"PFMT64d" 0x%08"PFMT64x" %10"PFMT64d" "
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s% %s.%s\n",
i, section->paddr, section->size, addr, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
} else {
#if 0
r_cons_printf ("idx=%02i vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"perm=%s %s%sname=%s\n",
i, addr, section->paddr, section->size, section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
#endif
// r_cons_printf ("%02i 0x%08"PFMT64x" %10"PFMT64d" 0x%08"PFMT64x" %10"PFMT64d" "
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s%s%s\n",
i, section->paddr, (ut64)section->size, addr, (ut64)section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
}
free (hashstr);
}
i++;
if (printHere) {
break;
}
}
if (r->bin && r->bin->cur && r->io && !r_io_desc_is_dbg (r->io->desc)) {
r_io_section_apply_bin (r->io, r->bin->cur->id, R_IO_SECTION_APPLY_FOR_ANALYSIS);
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_println ("]");
} else if (IS_MODE_NORMAL (mode) && !at && !printHere) {
// r_cons_printf ("\n%i sections\n", i);
}
ret = true;
out:
ht_free (dup_chk_ht);
return ret;
}
static int bin_fields(RCore *r, int mode, int va) {
RList *fields;
RListIter *iter;
RBinField *field;
int i = 0;
RBin *bin = r->bin;
RBinFile *binfile = r_core_bin_cur (r);
ut64 size = binfile ? binfile->size : UT64_MAX;
ut64 baddr = r_bin_get_baddr (r->bin);
if (!(fields = r_bin_get_fields (bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs header");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Header fields]");
}
//why this? there is an overlap in bin_sections with ehdr
//because there can't be two sections with the same name
#if 0
else if (IS_MODE_SET (mode)) {
// XXX: Need more flags??
// this will be set even if the binary does not have an ehdr
int fd = r_core_file_cur_fd(r);
r_io_section_add (r->io, 0, baddr, size, size, 7, "ehdr", 0, fd);
}
#endif
r_list_foreach (fields, iter, field) {
ut64 addr = rva (bin, field->paddr, field->vaddr, va);
if (IS_MODE_RAD (mode)) {
r_name_filter (field->name, -1);
r_cons_printf ("f header.%s @ 0x%08"PFMT64x"\n", field->name, addr);
if (field->comment && *field->comment) {
r_cons_printf ("CC %s @ 0x%"PFMT64x"\n", field->comment, addr);
}
if (field->format && *field->format) {
r_cons_printf ("pf.%s %s\n", field->name, field->format);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"name\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d,
iter->p? ",": "",
field->name,
field->vaddr,
field->paddr
);
if (field->comment && *field->comment) {
// TODO: filter comment before json
r_cons_printf (",\"comment\":\"%s\"", field->comment);
}
if (field->format && *field->format) {
// TODO: filter comment before json
r_cons_printf (",\"format\":\"%s\"", field->format);
}
r_cons_printf ("}");
} else if (IS_MODE_NORMAL (mode)) {
const bool haveComment = (field->comment && *field->comment);
r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s%s%s\n",
field->vaddr, field->paddr, field->name,
haveComment? "; ": "",
haveComment? field->comment: "");
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_RAD (mode)) {
/* add program header section */
r_cons_printf ("S 0 0x%"PFMT64x" 0x%"PFMT64x" 0x%"PFMT64x" ehdr rwx\n",
baddr, size, size);
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i fields\n", i);
}
return true;
}
static char* get_rp (const char* rtype) {
char *rp = NULL;
switch(rtype[0]) {
case 'v':
rp = strdup ("void");
break;
case 'c':
rp = strdup ("char");
break;
case 'i':
rp = strdup ("int");
break;
case 's':
rp = strdup ("short");
break;
case 'l':
rp = strdup ("long");
break;
case 'q':
rp = strdup ("long long");
break;
case 'C':
rp = strdup ("unsigned char");
break;
case 'I':
rp = strdup ("unsigned int");
break;
case 'S':
rp = strdup ("unsigned short");
break;
case 'L':
rp = strdup ("unsigned long");
break;
case 'Q':
rp = strdup ("unsigned long long");
break;
case 'f':
rp = strdup ("float");
break;
case 'd':
rp = strdup ("double");
break;
case 'D':
rp = strdup ("long double");
break;
case 'B':
rp = strdup ("bool");
break;
case '#':
rp = strdup ("CLASS");
break;
default:
rp = strdup ("unknown");
break;
}
return rp;
}
static int bin_classes(RCore *r, int mode) {
RListIter *iter, *iter2, *iter3;
RBinSymbol *sym;
RBinClass *c;
RBinField *f;
char *name;
RList *cs = r_bin_get_classes (r->bin);
if (!cs) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
// XXX: support for classes is broken and needs more love
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
if (!r_config_get_i (r->config, "bin.classes")) {
return false;
}
r_flag_space_set (r->flags, "classes");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs classes");
}
r_list_foreach (cs, iter, c) {
if (!c || !c->name || !c->name[0]) {
continue;
}
name = strdup (c->name);
r_name_filter (name, 0);
ut64 at_min = UT64_MAX;
ut64 at_max = 0LL;
r_list_foreach (c->methods, iter2, sym) {
if (sym->vaddr) {
if (sym->vaddr < at_min) {
at_min = sym->vaddr;
}
if (sym->vaddr + sym->size > at_max) {
at_max = sym->vaddr + sym->size;
}
}
}
if (at_min == UT64_MAX) {
at_min = c->addr;
at_max = c->addr; // XXX + size?
}
if (IS_MODE_SET (mode)) {
const char *classname = sdb_fmt ("class.%s", name);
r_flag_set (r->flags, classname, c->addr, 1);
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *method = sdb_fmt ("method%s.%s.%s",
mflags, c->name, sym->name);
R_FREE (mflags);
r_name_filter (method, -1);
r_flag_set (r->flags, method, sym->vaddr, 1);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %s%s%s\n",
c->addr, at_min, at_max, c->name, c->super ? " " : "",
c->super ? c->super : "");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("\"f class.%s = 0x%"PFMT64x"\"\n",
name, at_min);
if (c->super) {
r_cons_printf ("\"f super.%s.%s = %d\"\n",
c->name, c->super, c->index);
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *cmd = r_str_newf ("\"f method%s.%s.%s = 0x%"PFMT64x"\"\n", mflags, c->name, sym->name, sym->vaddr);
r_str_replace_char (cmd, '\n', 0);
r_cons_printf ("%s\n", cmd);
R_FREE (mflags);
free (cmd);
}
} else if (IS_MODE_JSON (mode)) {
if (c->super) {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"super\":\"%s\",\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index, c->super);
} else {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index);
}
r_list_foreach (c->methods, iter2, sym) {
if (sym->method_flags) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, mflags, sym->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, sym->vaddr);
}
}
r_cons_printf ("], \"fields\":[");
r_list_foreach (c->fields, iter3, f) {
if (f->flags) {
char *mflags = r_core_bin_method_flags_str (f->flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, mflags, f->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, f->vaddr);
}
}
r_cons_printf ("]}");
} else if (IS_MODE_CLASSDUMP (mode)) {
char *rp = NULL;
if (c) {
//TODO -> Print Superclass
r_cons_printf ("@interface %s : \n{\n", c->name);
r_list_foreach (c->fields, iter2, f) {
if (f->name && r_regex_match ("ivar","e", f->name)) {
r_cons_printf (" %s %s\n", f->type, f->name);
}
}
r_cons_printf ("}\n");
r_list_foreach (c->methods, iter3, sym) {
if (sym->rtype && sym->rtype[0] != '@') {
rp = get_rp (sym->rtype);
r_cons_printf ("%s (%s) %s\n", strncmp (sym->type,"METH",4) ? "+": "-", rp, sym->dname? sym->dname: sym->name);
}
}
r_cons_printf ("@end\n");
}
} else {
int m = 0;
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] (sz %"PFMT64d") class %d %s",
c->addr, at_min, at_max, (at_max - at_min), c->index, c->name);
if (c->super) {
r_cons_printf (" super: %s\n", c->super);
} else {
r_cons_newline ();
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("0x%08"PFMT64x" method %d %s %s\n",
sym->vaddr, m, mflags, sym->dname? sym->dname: sym->name);
R_FREE (mflags);
m++;
}
}
free (name);
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
return true;
}
static int bin_size(RCore *r, int mode) {
ut64 size = r_bin_get_size (r->bin);
if (IS_MODE_SIMPLE (mode) || IS_MODE_JSON (mode)) {
r_cons_printf ("%"PFMT64u"\n", size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f bin_size @ %"PFMT64u"\n", size);
} else if (IS_MODE_SET (mode)) {
r_core_cmdf (r, "f bin_size @ %"PFMT64u"\n", size);
} else {
r_cons_printf ("%"PFMT64u"\n", size);
}
return true;
}
static int bin_libs(RCore *r, int mode) {
RList *libs;
RListIter *iter;
char* lib;
int i = 0;
if (!(libs = r_bin_get_libs (r->bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Linked libraries]");
}
r_list_foreach (libs, iter, lib) {
if (IS_MODE_SET (mode)) {
// Nothing to set.
// TODO: load libraries with iomaps?
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("CCa entry0 %s\n", lib);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s\"%s\"", iter->p ? "," : "", lib);
} else {
// simple and normal print mode
r_cons_println (lib);
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
if (i == 1) {
r_cons_printf ("\n%i library\n", i);
} else {
r_cons_printf ("\n%i libraries\n", i);
}
}
return true;
}
static void bin_mem_print(RList *mems, int perms, int depth, int mode) {
RBinMem *mem;
RListIter *iter;
if (!mems) {
return;
}
r_list_foreach (mems, iter, mem) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"name\":\"%s\",\"size\":%d,\"address\":%d,"
"\"flags\":\"%s\"}", mem->name, mem->size,
mem->addr, r_str_rwx_i (mem->perms & perms));
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", mem->addr);
} else {
r_cons_printf ("0x%08"PFMT64x" +0x%04x %s %*s%-*s\n",
mem->addr, mem->size, r_str_rwx_i (mem->perms & perms),
depth, "", 20-depth, mem->name);
}
if (mem->mirrors) {
if (IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
bin_mem_print (mem->mirrors, mem->perms & perms, depth + 1, mode);
}
if (IS_MODE_JSON(mode)) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
static int bin_mem(RCore *r, int mode) {
RList *mem = NULL;
if (!r) return false;
if (!IS_MODE_JSON(mode)) {
if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
r_cons_println ("[Memory]\n");
}
}
if (!(mem = r_bin_get_mem (r->bin))) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
bin_mem_print (mem, 7, 0, R_CORE_BIN_JSON);
r_cons_println ("]");
return true;
} else if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
bin_mem_print (mem, 7, 0, mode);
}
return true;
}
static void bin_pe_versioninfo(RCore *r, int mode) {
Sdb *sdb = NULL;
int num_version = 0;
int num_stringtable = 0;
int num_string = 0;
const char *format_version = "bin/cur/info/vs_version_info/VS_VERSIONINFO%d";
const char *format_stringtable = "%s/string_file_info/stringtable%d";
const char *format_string = "%s/string%d";
if (!IS_MODE_JSON (mode)) {
r_cons_printf ("=== VS_VERSIONINFO ===\n\n");
}
bool firstit_dowhile = true;
do {
char path_version[256] = R_EMPTY;
snprintf (path_version, sizeof (path_version), format_version, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (!firstit_dowhile && IS_MODE_JSON (mode)) { r_cons_printf (","); }
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"VS_FIXEDFILEINFO\":{");
} else {
r_cons_printf ("# VS_FIXEDFILEINFO\n\n");
}
char path_fixedfileinfo[256] = R_EMPTY;
snprintf (path_fixedfileinfo, sizeof (path_fixedfileinfo), "%s/fixed_file_info", path_version);
if (!(sdb = sdb_ns_path (r->sdb, path_fixedfileinfo, 0))) {
r_cons_printf ("}");
break;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"Signature\":%"PFMT64u",", sdb_num_get (sdb, "Signature", 0));
} else {
r_cons_printf (" Signature: 0x%"PFMT64x"\n", sdb_num_get (sdb, "Signature", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"StrucVersion\":%"PFMT64u",", sdb_num_get (sdb, "StrucVersion", 0));
} else {
r_cons_printf (" StrucVersion: 0x%"PFMT64x"\n", sdb_num_get (sdb, "StrucVersion", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
} else {
r_cons_printf (" FileVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"ProductVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
} else {
r_cons_printf (" ProductVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileFlagsMask\":%"PFMT64u",", sdb_num_get (sdb, "FileFlagsMask", 0));
} else {
r_cons_printf (" FileFlagsMask: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlagsMask", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileFlags\":%"PFMT64u",", sdb_num_get (sdb, "FileFlags", 0));
} else {
r_cons_printf (" FileFlags: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlags", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileOS\":%"PFMT64u",", sdb_num_get (sdb, "FileOS", 0));
} else {
r_cons_printf (" FileOS: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileOS", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileType\":%"PFMT64u",", sdb_num_get (sdb, "FileType", 0));
} else {
r_cons_printf (" FileType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileType", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileSubType\":%"PFMT64u, sdb_num_get (sdb, "FileSubType", 0));
} else {
r_cons_printf (" FileSubType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileSubType", 0));
}
#if 0
r_cons_printf (" FileDate: %d.%d.%d.%d\n",
sdb_num_get (sdb, "FileDateMS", 0) >> 16,
sdb_num_get (sdb, "FileDateMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileDateLS", 0) >> 16,
sdb_num_get (sdb, "FileDateLS", 0) & 0xFFFF);
#endif
if (IS_MODE_JSON (mode)) {
r_cons_printf ("},");
} else {
r_cons_newline ();
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"StringTable\":{");
} else {
r_cons_printf ("# StringTable\n\n");
}
for (num_stringtable = 0; sdb; num_stringtable++) {
char path_stringtable[256] = R_EMPTY;
snprintf (path_stringtable, sizeof (path_stringtable), format_stringtable, path_version, num_stringtable);
sdb = sdb_ns_path (r->sdb, path_stringtable, 0);
bool firstit_for = true;
for (num_string = 0; sdb; num_string++) {
char path_string[256] = R_EMPTY;
snprintf (path_string, sizeof (path_string), format_string, path_stringtable, num_string);
sdb = sdb_ns_path (r->sdb, path_string, 0);
if (sdb) {
if (!firstit_for && IS_MODE_JSON (mode)) { r_cons_printf (","); }
int lenkey = 0;
int lenval = 0;
ut8 *key_utf16 = sdb_decode (sdb_const_get (sdb, "key", 0), &lenkey);
ut8 *val_utf16 = sdb_decode (sdb_const_get (sdb, "value", 0), &lenval);
ut8 *key_utf8 = calloc (lenkey * 2, 1);
ut8 *val_utf8 = calloc (lenval * 2, 1);
if (r_str_utf16_to_utf8 (key_utf8, lenkey * 2, key_utf16, lenkey, true) < 0
|| r_str_utf16_to_utf8 (val_utf8, lenval * 2, val_utf16, lenval, true) < 0) {
eprintf ("Warning: Cannot decode utf16 to utf8\n");
} else if (IS_MODE_JSON (mode)) {
char *escaped_key_utf8 = r_str_escape ((char*)key_utf8);
char *escaped_val_utf8 = r_str_escape ((char*)val_utf8);
r_cons_printf ("\"%s\":\"%s\"", escaped_key_utf8, escaped_val_utf8);
free (escaped_key_utf8);
free (escaped_val_utf8);
} else {
r_cons_printf (" %s: %s\n", (char*)key_utf8, (char*)val_utf8);
}
free (key_utf8);
free (val_utf8);
free (key_utf16);
free (val_utf16);
}
firstit_for = false;
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("}}");
}
num_version++;
firstit_dowhile = false;
} while (sdb);
}
static void bin_elf_versioninfo(RCore *r, int mode) {
const char *format = "bin/cur/info/versioninfo/%s%d";
char path[256] = {0};
int num_versym = 0;
int num_verneed = 0;
int num_version = 0;
Sdb *sdb = NULL;
const char *oValue = NULL;
bool firstit_for_versym = true;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"versym\":[");
}
for (;; num_versym++) {
snprintf (path, sizeof (path), format, "versym", num_versym);
if (!(sdb = sdb_ns_path (r->sdb, path, 0))) {
break;
}
ut64 addr = sdb_num_get (sdb, "addr", 0);
ut64 offset = sdb_num_get (sdb, "offset", 0);
ut64 link = sdb_num_get (sdb, "link", 0);
ut64 num_entries = sdb_num_get (sdb, "num_entries", 0);
const char *section_name = sdb_const_get (sdb, "section_name", 0);
const char *link_section_name = sdb_const_get (sdb, "link_section_name", 0);
if (IS_MODE_JSON (mode)) {
if (!firstit_for_versym) { r_cons_printf (","); }
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
section_name, (ut64)addr, (ut64)offset);
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
(ut32)link, link_section_name);
} else {
r_cons_printf ("Version symbols section '%s' contains %"PFMT64u" entries:\n", section_name, num_entries);
r_cons_printf (" Addr: 0x%08"PFMT64x" Offset: 0x%08"PFMT64x" Link: %x (%s)\n",
(ut64)addr, (ut64)offset, (ut32)link, link_section_name);
}
int i;
for (i = 0; i < num_entries; i++) {
char key[32] = R_EMPTY;
snprintf (key, sizeof (key), "entry%d", i);
const char *value = sdb_const_get (sdb, key, 0);
if (value) {
if (oValue && !strcmp (value, oValue)) {
continue;
}
if (IS_MODE_JSON (mode)) {
if (i > 0) { r_cons_printf (","); }
char *escaped_value = r_str_escape (value);
r_cons_printf ("{\"idx\":%"PFMT64u",\"value\":\"%s\"}",
(ut64) i, escaped_value);
free (escaped_value);
} else {
r_cons_printf (" 0x%08"PFMT64x": ", (ut64) i);
r_cons_printf ("%s\n", value);
}
oValue = value;
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
} else {
r_cons_printf ("\n\n");
}
firstit_for_versym = false;
}
if (IS_MODE_JSON (mode)) { r_cons_printf ("],\"verneed\":["); }
bool firstit_dowhile_verneed = true;
do {
char path_version[256] = R_EMPTY;
snprintf (path, sizeof (path), format, "verneed", num_verneed++);
if (!(sdb = sdb_ns_path (r->sdb, path, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_verneed) { r_cons_printf (","); }
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
sdb_const_get (sdb, "section_name", 0), sdb_num_get (sdb, "addr", 0), sdb_num_get (sdb, "offset", 0));
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
sdb_num_get (sdb, "link", 0), sdb_const_get (sdb, "link_section_name", 0));
} else {
r_cons_printf ("Version need section '%s' contains %d entries:\n",
sdb_const_get (sdb, "section_name", 0), (int)sdb_num_get (sdb, "num_entries", 0));
r_cons_printf (" Addr: 0x%08"PFMT64x, sdb_num_get (sdb, "addr", 0));
r_cons_printf (" Offset: 0x%08"PFMT64x" Link to section: %"PFMT64d" (%s)\n",
sdb_num_get (sdb, "offset", 0), sdb_num_get (sdb, "link", 0),
sdb_const_get (sdb, "link_section_name", 0));
}
bool firstit_for_verneed = true;
for (num_version = 0;; num_version++) {
snprintf (path_version, sizeof (path_version), "%s/version%d", path, num_version);
const char *filename = NULL;
char path_vernaux[256] = R_EMPTY;
int num_vernaux = 0;
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_for_verneed) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64u",\"vn_version\":%d,",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Version: %d",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
}
if ((filename = sdb_const_get (sdb, "file_name", 0))) {
if (IS_MODE_JSON (mode)) {
char *escaped_filename = r_str_escape (filename);
r_cons_printf ("\"file_name\":\"%s\",", escaped_filename);
free (escaped_filename);
} else {
r_cons_printf (" File: %s", filename);
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"cnt\":%d,", (int)sdb_num_get (sdb, "cnt", 0));
} else {
r_cons_printf (" Cnt: %d\n", (int)sdb_num_get (sdb, "cnt", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"vernaux\":[");
}
bool firstit_dowhile_vernaux = true;
do {
snprintf (path_vernaux, sizeof (path_vernaux), "%s/vernaux%d",
path_version, num_vernaux++);
if (!(sdb = sdb_ns_path (r->sdb, path_vernaux, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_vernaux) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64x",\"name\":\"%s\",",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf ("\"flags\":\"%s\",\"version\":%d}",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Name: %s",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf (" Flags: %s Version: %d\n",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
}
firstit_dowhile_vernaux = false;
} while (sdb);
if (IS_MODE_JSON (mode)) { r_cons_printf ("]}"); };
firstit_for_verneed = false;
}
if (IS_MODE_JSON (mode)) { r_cons_printf ("]}"); };
firstit_dowhile_verneed = false;
} while (sdb);
if (IS_MODE_JSON (mode)) { r_cons_printf ("]}"); }
}
static void bin_mach0_versioninfo(RCore *r) {
/* TODO */
}
static void bin_pe_resources(RCore *r, int mode) {
Sdb *sdb = NULL;
int index = 0;
const char *pe_path = "bin/cur/info/pe_resource";
if (!(sdb = sdb_ns_path (r->sdb, pe_path, 0))) {
return;
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "resources");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs resources\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
while (true) {
const char *timestrKey = sdb_fmt ("resource.%d.timestr", index);
const char *vaddrKey = sdb_fmt ("resource.%d.vaddr", index);
const char *sizeKey = sdb_fmt ("resource.%d.size", index);
const char *typeKey = sdb_fmt ("resource.%d.type", index);
const char *languageKey = sdb_fmt ("resource.%d.language", index);
const char *nameKey = sdb_fmt ("resource.%d.name", index);
char *timestr = sdb_get (sdb, timestrKey, 0);
if (!timestr) {
break;
}
ut64 vaddr = sdb_num_get (sdb, vaddrKey, 0);
int size = (int)sdb_num_get (sdb, sizeKey, 0);
int name = (int)sdb_num_get (sdb, nameKey, 0);
char *type = sdb_get (sdb, typeKey, 0);
char *lang = sdb_get (sdb, languageKey, 0);
if (IS_MODE_SET (mode)) {
const char *name = sdb_fmt ("resource.%d", index);
r_flag_set (r->flags, name, vaddr, size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f resource.%d %d 0x%08"PFMT32x"\n", index, size, vaddr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf("%s{\"name\":%d,\"index\":%d, \"type\":\"%s\","
"\"vaddr\":%"PFMT64d", \"size\":%d, \"lang\":\"%s\"}",
index? ",": "", name, index, type, vaddr, size, lang);
} else {
char *humanSize = r_num_units (NULL, size);
r_cons_printf ("Resource %d\n", index);
r_cons_printf (" name: %d\n", name);
r_cons_printf (" timestamp: %s\n", timestr);
r_cons_printf (" vaddr: 0x%08"PFMT64x"\n", vaddr);
if (humanSize) {
r_cons_printf (" size: %s\n", humanSize);
}
r_cons_printf (" type: %s\n", type);
r_cons_printf (" language: %s\n", lang);
free (humanSize);
}
R_FREE (timestr);
R_FREE (type);
R_FREE (lang)
index++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs *");
}
}
static void bin_no_resources(RCore *r, int mode) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[]");
}
}
static int bin_resources(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_resources (r, mode);
} else {
bin_no_resources (r, mode);
}
return true;
}
static int bin_versioninfo(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_versioninfo (r, mode);
} else if (!strncmp ("elf", info->rclass, 3)) {
bin_elf_versioninfo (r, mode);
} else if (!strncmp ("mach0", info->rclass, 5)) {
bin_mach0_versioninfo (r);
} else {
r_cons_println ("Unknown format");
return false;
}
return true;
}
static int bin_signature(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->signature) {
const char *signature = plg->signature (cur, IS_MODE_JSON (mode));
r_cons_println (signature);
free ((char*) signature);
return true;
}
return false;
}
R_API void r_core_bin_export_info_rad(RCore *core) {
Sdb *db = NULL;
char *flagname = NULL, *offset = NULL;
RBinFile *bf = r_core_bin_cur (core);
if (!bf) {
return;
}
db = sdb_ns (bf->sdb, "info", 0);;
if (!db) {
return;
}
if (db) {
SdbListIter *iter;
SdbKv *kv;
r_cons_printf ("fs format\n");
// iterate over all keys
SdbList *ls = sdb_foreach_list (db, false);
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
//printf ("?e (%s) (%s)\n", k, v);
if ((flagname = strstr (dup, ".offset"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("f %s @ %s\n", flagname, v);
free (offset);
offset = strdup (v);
}
if ((flagname = strstr (dup, ".cparse"))) {
r_cons_printf ("\"td %s\"\n", v);
}
free (dup);
}
R_FREE (offset);
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
r_cons_printf ("pf.%s %s\n", flagname, v);
}
free (dup);
}
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
int fmtsize = r_print_format_struct_size (v, core->print, 0, 0);
char *offset_key = r_str_newf ("%s.offset", flagname);
const char *off = sdb_const_get (db, offset_key, 0);
free (offset_key);
if (off) {
r_cons_printf ("Cf %d %s @ %s\n", fmtsize, v, off);
}
}
if ((flagname = strstr (dup, ".size"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("fl %s %s\n", flagname, v);
}
}
free (offset);
}
}
static int bin_header(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->header) {
plg->header (cur);
return true;
}
return false;
}
R_API int r_core_bin_info(RCore *core, int action, int mode, int va, RCoreBinFilter *filter, const char *chksum) {
int ret = true;
const char *name = NULL;
ut64 at = 0, loadaddr = r_bin_get_laddr (core->bin);
if (filter && filter->offset) {
at = filter->offset;
}
if (filter && filter->name) {
name = filter->name;
}
// use our internal values for va
va = va ? VA_TRUE : VA_FALSE;
#if 0
if (r_config_get_i (core->config, "anal.strings")) {
r_core_cmd0 (core, "aar");
}
#endif
if ((action & R_CORE_BIN_ACC_STRINGS)) ret &= bin_strings (core, mode, va);
if ((action & R_CORE_BIN_ACC_RAW_STRINGS)) ret &= bin_raw_strings (core, mode, va);
if ((action & R_CORE_BIN_ACC_INFO)) ret &= bin_info (core, mode);
if ((action & R_CORE_BIN_ACC_MAIN)) ret &= bin_main (core, mode, va);
if ((action & R_CORE_BIN_ACC_DWARF)) ret &= bin_dwarf (core, mode);
if ((action & R_CORE_BIN_ACC_PDB)) ret &= bin_pdb (core, mode);
if ((action & R_CORE_BIN_ACC_ENTRIES)) ret &= bin_entry (core, mode, loadaddr, va, false);
if ((action & R_CORE_BIN_ACC_INITFINI)) ret &= bin_entry (core, mode, loadaddr, va, true);
if ((action & R_CORE_BIN_ACC_SECTIONS)) ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum);
if (r_config_get_i (core->config, "bin.relocs")) {
if ((action & R_CORE_BIN_ACC_RELOCS)) ret &= bin_relocs (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_IMPORTS)) ret &= bin_imports (core, mode, va, name); // 6s
if ((action & R_CORE_BIN_ACC_EXPORTS)) ret &= bin_exports (core, mode, loadaddr, va, at, name, chksum);
if ((action & R_CORE_BIN_ACC_SYMBOLS)) ret &= bin_symbols (core, mode, loadaddr, va, at, name, chksum); // 6s
if ((action & R_CORE_BIN_ACC_LIBS)) ret &= bin_libs (core, mode);
if ((action & R_CORE_BIN_ACC_CLASSES)) ret &= bin_classes (core, mode); // 3s
if ((action & R_CORE_BIN_ACC_SIZE)) ret &= bin_size (core, mode);
if ((action & R_CORE_BIN_ACC_MEM)) ret &= bin_mem (core, mode);
if ((action & R_CORE_BIN_ACC_VERSIONINFO)) ret &= bin_versioninfo (core, mode);
if ((action & R_CORE_BIN_ACC_RESOURCES)) ret &= bin_resources (core, mode);
if ((action & R_CORE_BIN_ACC_SIGNATURE)) ret &= bin_signature (core, mode);
if ((action & R_CORE_BIN_ACC_FIELDS)) {
if (IS_MODE_SIMPLE (mode)) {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
/* ignore mode, just for quiet/simple here */
ret &= bin_fields (core, 0, va);
}
} else {
if (IS_MODE_NORMAL (mode)) {
ret &= bin_header (core, mode);
} else {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
ret &= bin_fields (core, mode, va);
}
}
}
}
return ret;
}
R_API int r_core_bin_set_arch_bits(RCore *r, const char *name, const char * arch, ut16 bits) {
int fd = r_io_fd_get_current (r->io);
RIODesc *desc = r_io_desc_get (r->io, fd);
RBinFile *curfile, *binfile = NULL;
if (!name) {
name = (desc) ? desc->name : NULL;
}
if (!name) {
return false;
}
/* Check if the arch name is a valid name */
if (!r_asm_is_valid (r->assembler, arch)) {
return false;
}
/* Find a file with the requested name/arch/bits */
binfile = r_bin_file_find_by_arch_bits (r->bin, arch, bits, name);
if (!binfile) {
return false;
}
if (!r_bin_use_arch (r->bin, arch, bits, name)) {
return false;
}
curfile = r_bin_cur (r->bin);
//set env if the binfile changed or we are dealing with xtr
if (curfile != binfile || binfile->curxtr) {
r_core_bin_set_cur (r, binfile);
return r_core_bin_set_env (r, binfile);
}
return true;
}
R_API int r_core_bin_update_arch_bits(RCore *r) {
RBinFile *binfile = NULL;
const char *name = NULL, *arch = NULL;
ut16 bits = 0;
if (!r) {
return 0;
}
if (r->assembler) {
bits = r->assembler->bits;
if (r->assembler->cur) {
arch = r->assembler->cur->arch;
}
}
binfile = r_core_bin_cur (r);
name = binfile ? binfile->file : NULL;
if (binfile && binfile->curxtr) {
r_anal_hint_clear (r->anal);
}
return r_core_bin_set_arch_bits (r, name, arch, bits);
}
R_API int r_core_bin_raise(RCore *core, ut32 binfile_idx, ut32 binobj_idx) {
RBin *bin = core->bin;
RBinFile *binfile = NULL;
if (binfile_idx == UT32_MAX && binobj_idx == UT32_MAX) {
return false;
}
if (!r_bin_select_by_ids (bin, binfile_idx, binobj_idx)) {
return false;
}
binfile = r_core_bin_cur (core);
if (binfile) {
r_io_use_fd (core->io, binfile->fd);
}
// it should be 0 to use r_io_use_fd in r_core_block_read
core->switch_file_view = 0;
return binfile && r_core_bin_set_env (core, binfile) && r_core_block_read (core);
}
R_API bool r_core_bin_delete(RCore *core, ut32 binfile_idx, ut32 binobj_idx) {
if (binfile_idx == UT32_MAX && binobj_idx == UT32_MAX) {
return false;
}
if (!r_bin_object_delete (core->bin, binfile_idx, binobj_idx)) {
return false;
}
RBinFile *binfile = r_core_bin_cur (core);
if (binfile) {
r_io_use_fd (core->io, binfile->fd);
}
core->switch_file_view = 0;
return binfile && r_core_bin_set_env (core, binfile) && r_core_block_read (core);
}
static int r_core_bin_file_print(RCore *core, RBinFile *binfile, int mode) {
RListIter *iter;
RBinObject *obj;
const char *name = binfile ? binfile->file : NULL;
(void)r_bin_get_info (core->bin); // XXX is this necssary for proper iniitialization
ut32 id = binfile ? binfile->id : 0;
ut32 fd = binfile ? binfile->fd : 0;
ut32 bin_sz = binfile ? binfile->size : 0;
// TODO: handle mode to print in json and r2 commands
if (!binfile) {
return false;
}
switch (mode) {
case '*':
r_list_foreach (binfile->objs, iter, obj) {
r_cons_printf ("oba 0x%08"PFMT64x" %s # %d\n", obj->boffset, name, obj->id);
}
break;
case 'q':
r_list_foreach (binfile->objs, iter, obj) {
r_cons_printf ("%d\n", obj->id);
}
break;
case 'j':
r_cons_printf ("{\"name\":\"%s\",\"fd\":%d,\"id\":%d,\"size\":%d,\"objs\":[",
name, fd, id, bin_sz);
r_list_foreach (binfile->objs, iter, obj) {
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *arch = info ? info->arch : "unknown";
r_cons_printf ("{\"objid\":%d,\"arch\":\"%s\",\"bits\":%d,\"binoffset\":%"
PFMT64d",\"objsize\":%"PFMT64d"}",
obj->id, arch, bits, obj->boffset, obj->obj_size);
if (iter->n) {
r_cons_print (",");
}
}
r_cons_print ("]}");
break;
default:
r_list_foreach (binfile->objs, iter, obj) {
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *arch = info ? info->arch : "unknown";
if (!arch) {
arch = r_config_get (core->config, "asm.arch");
}
r_cons_printf ("%4d %s-%d at:0x%08"PFMT64x" sz:%"PFMT64d" ",
obj->id, arch, bits, obj->boffset, obj->obj_size );
r_cons_printf ("fd:%d %s\n", fd, name);
}
break;
}
return true;
}
R_API int r_core_bin_list(RCore *core, int mode) {
// list all binfiles and there objects and there archs
int count = 0;
RListIter *iter;
RBinFile *binfile = NULL; //, *cur_bf = r_core_bin_cur (core) ;
RBin *bin = core->bin;
const RList *binfiles = bin ? bin->binfiles: NULL;
if (!binfiles) {
return false;
}
if (mode == 'j') {
r_cons_print ("[");
}
r_list_foreach (binfiles, iter, binfile) {
r_core_bin_file_print (core, binfile, mode);
if (iter->n && mode == 'j') {
r_cons_print (",");
}
}
if (mode == 'j') {
r_cons_println ("]");
}
//r_core_file_set_by_file (core, cur_cf);
//r_core_bin_bind (core, cur_bf);
return count;
}
R_API char *r_core_bin_method_flags_str(ut64 flags, int mode) {
char *str;
RStrBuf *buf;
int i, len = 0;
buf = r_strbuf_new ("");
if (IS_MODE_SET (mode) || IS_MODE_RAD (mode)) {
if (!flags) {
goto out;
}
for (i = 0; i != 64; i++) {
ut64 flag = flags & (1UL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (flag_string) {
r_strbuf_appendf (buf, ".%s", flag_string);
}
}
}
} else if (IS_MODE_JSON (mode)) {
if (!flags) {
r_strbuf_append (buf, "[]");
goto out;
}
r_strbuf_append (buf, "[");
for (i = 0; i != 64; i++) {
ut64 flag = flags & (1LL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (len != 0) {
r_strbuf_append (buf, ",");
}
if (flag_string) {
r_strbuf_appendf (buf, "\"%s\"", flag_string);
} else {
r_strbuf_appendf (buf, "\"0x%08"PFMT64x"\"", flag);
}
len++;
}
}
r_strbuf_append (buf, "]");
} else {
int pad_len = 4; //TODO: move to a config variable
if (!flags) {
goto padding;
}
for (i = 0; i != 64; i++) {
ut64 flag = flags & (1L << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, true);
if (flag_string) {
r_strbuf_append (buf, flag_string);
} else {
r_strbuf_append (buf, "?");
}
len++;
}
}
padding:
for ( ; len < pad_len; len++) {
r_strbuf_append (buf, " ");
}
}
out:
str = strdup (r_strbuf_get (buf));
r_strbuf_free (buf);
return str;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_140_1 |
crossvul-cpp_data_bad_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_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/bad_263_0 |
crossvul-cpp_data_bad_3942_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Cliprdr common
*
* Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
* Copyright 2019 Kobi Mizrachi <kmizrachi18@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.
*/
#include <winpr/crt.h>
#include <winpr/stream.h>
#include <freerdp/channels/log.h>
#define TAG CHANNELS_TAG("cliprdr.common")
#include "cliprdr_common.h"
static BOOL cliprdr_validate_file_contents_request(const CLIPRDR_FILE_CONTENTS_REQUEST* request)
{
/*
* [MS-RDPECLIP] 2.2.5.3 File Contents Request PDU (CLIPRDR_FILECONTENTS_REQUEST).
*
* A request for the size of the file identified by the lindex field. The size MUST be
* returned as a 64-bit, unsigned integer. The cbRequested field MUST be set to
* 0x00000008 and both the nPositionLow and nPositionHigh fields MUST be
* set to 0x00000000.
*/
if (request->dwFlags & FILECONTENTS_SIZE)
{
if (request->cbRequested != sizeof(UINT64))
{
WLog_ERR(TAG, "[%s]: cbRequested must be %" PRIu32 ", got %" PRIu32 "", __FUNCTION__,
sizeof(UINT64), request->cbRequested);
return FALSE;
}
if (request->nPositionHigh != 0 || request->nPositionLow != 0)
{
WLog_ERR(TAG, "[%s]: nPositionHigh and nPositionLow must be set to 0", __FUNCTION__);
return FALSE;
}
}
return TRUE;
}
wStream* cliprdr_packet_new(UINT16 msgType, UINT16 msgFlags, UINT32 dataLen)
{
wStream* s;
s = Stream_New(NULL, dataLen + 8);
if (!s)
{
WLog_ERR(TAG, "Stream_New failed!");
return NULL;
}
Stream_Write_UINT16(s, msgType);
Stream_Write_UINT16(s, msgFlags);
/* Write actual length after the entire packet has been constructed. */
Stream_Seek(s, 4);
return s;
}
static void cliprdr_write_file_contents_request(wStream* s,
const CLIPRDR_FILE_CONTENTS_REQUEST* request)
{
Stream_Write_UINT32(s, request->streamId); /* streamId (4 bytes) */
Stream_Write_UINT32(s, request->listIndex); /* listIndex (4 bytes) */
Stream_Write_UINT32(s, request->dwFlags); /* dwFlags (4 bytes) */
Stream_Write_UINT32(s, request->nPositionLow); /* nPositionLow (4 bytes) */
Stream_Write_UINT32(s, request->nPositionHigh); /* nPositionHigh (4 bytes) */
Stream_Write_UINT32(s, request->cbRequested); /* cbRequested (4 bytes) */
if (request->haveClipDataId)
Stream_Write_UINT32(s, request->clipDataId); /* clipDataId (4 bytes) */
}
static INLINE void cliprdr_write_lock_unlock_clipdata(wStream* s, UINT32 clipDataId)
{
Stream_Write_UINT32(s, clipDataId);
}
static void cliprdr_write_lock_clipdata(wStream* s,
const CLIPRDR_LOCK_CLIPBOARD_DATA* lockClipboardData)
{
cliprdr_write_lock_unlock_clipdata(s, lockClipboardData->clipDataId);
}
static void cliprdr_write_unlock_clipdata(wStream* s,
const CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData)
{
cliprdr_write_lock_unlock_clipdata(s, unlockClipboardData->clipDataId);
}
static void cliprdr_write_file_contents_response(wStream* s,
const CLIPRDR_FILE_CONTENTS_RESPONSE* response)
{
Stream_Write_UINT32(s, response->streamId); /* streamId (4 bytes) */
Stream_Write(s, response->requestedData, response->cbRequested);
}
wStream* cliprdr_packet_lock_clipdata_new(const CLIPRDR_LOCK_CLIPBOARD_DATA* lockClipboardData)
{
wStream* s;
if (!lockClipboardData)
return NULL;
s = cliprdr_packet_new(CB_LOCK_CLIPDATA, 0, 4);
if (!s)
return NULL;
cliprdr_write_lock_clipdata(s, lockClipboardData);
return s;
}
wStream*
cliprdr_packet_unlock_clipdata_new(const CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData)
{
wStream* s;
if (!unlockClipboardData)
return NULL;
s = cliprdr_packet_new(CB_LOCK_CLIPDATA, 0, 4);
if (!s)
return NULL;
cliprdr_write_unlock_clipdata(s, unlockClipboardData);
return s;
}
wStream* cliprdr_packet_file_contents_request_new(const CLIPRDR_FILE_CONTENTS_REQUEST* request)
{
wStream* s;
if (!request)
return NULL;
s = cliprdr_packet_new(CB_FILECONTENTS_REQUEST, 0, 28);
if (!s)
return NULL;
cliprdr_write_file_contents_request(s, request);
return s;
}
wStream* cliprdr_packet_file_contents_response_new(const CLIPRDR_FILE_CONTENTS_RESPONSE* response)
{
wStream* s;
if (!response)
return NULL;
s = cliprdr_packet_new(CB_FILECONTENTS_RESPONSE, response->msgFlags, 4 + response->cbRequested);
if (!s)
return NULL;
cliprdr_write_file_contents_response(s, response);
return s;
}
wStream* cliprdr_packet_format_list_new(const CLIPRDR_FORMAT_LIST* formatList,
BOOL useLongFormatNames)
{
wStream* s;
UINT32 index;
int cchWideChar;
LPWSTR lpWideCharStr;
int formatNameSize;
char* szFormatName;
WCHAR* wszFormatName;
BOOL asciiNames = FALSE;
CLIPRDR_FORMAT* format;
if (formatList->msgType != CB_FORMAT_LIST)
WLog_WARN(TAG, "[%s] called with invalid type %08" PRIx32, __FUNCTION__,
formatList->msgType);
if (!useLongFormatNames)
{
UINT32 length = formatList->numFormats * 36;
s = cliprdr_packet_new(CB_FORMAT_LIST, 0, length);
if (!s)
{
WLog_ERR(TAG, "cliprdr_packet_new failed!");
return NULL;
}
for (index = 0; index < formatList->numFormats; index++)
{
size_t formatNameLength = 0;
format = (CLIPRDR_FORMAT*)&(formatList->formats[index]);
Stream_Write_UINT32(s, format->formatId); /* formatId (4 bytes) */
formatNameSize = 0;
szFormatName = format->formatName;
if (asciiNames)
{
if (szFormatName)
formatNameLength = strnlen(szFormatName, 32);
if (formatNameLength > 31)
formatNameLength = 31;
Stream_Write(s, szFormatName, formatNameLength);
Stream_Zero(s, 32 - formatNameLength);
}
else
{
wszFormatName = NULL;
if (szFormatName)
formatNameSize =
ConvertToUnicode(CP_UTF8, 0, szFormatName, -1, &wszFormatName, 0);
if (formatNameSize < 0)
return NULL;
if (formatNameSize > 15)
formatNameSize = 15;
/* size in bytes instead of wchar */
formatNameSize *= 2;
if (wszFormatName)
Stream_Write(s, wszFormatName, (size_t)formatNameSize);
Stream_Zero(s, (size_t)(32 - formatNameSize));
free(wszFormatName);
}
}
}
else
{
UINT32 length = 0;
for (index = 0; index < formatList->numFormats; index++)
{
format = (CLIPRDR_FORMAT*)&(formatList->formats[index]);
length += 4;
formatNameSize = 2;
if (format->formatName)
formatNameSize =
MultiByteToWideChar(CP_UTF8, 0, format->formatName, -1, NULL, 0) * 2;
if (formatNameSize < 0)
return NULL;
length += (UINT32)formatNameSize;
}
s = cliprdr_packet_new(CB_FORMAT_LIST, 0, length);
if (!s)
{
WLog_ERR(TAG, "cliprdr_packet_new failed!");
return NULL;
}
for (index = 0; index < formatList->numFormats; index++)
{
format = (CLIPRDR_FORMAT*)&(formatList->formats[index]);
Stream_Write_UINT32(s, format->formatId); /* formatId (4 bytes) */
if (format->formatName)
{
const size_t cap = Stream_Capacity(s);
const size_t pos = Stream_GetPosition(s);
const size_t rem = cap - pos;
if ((cap < pos) || ((rem / 2) > INT_MAX))
return NULL;
lpWideCharStr = (LPWSTR)Stream_Pointer(s);
cchWideChar = (int)(rem / 2);
formatNameSize = MultiByteToWideChar(CP_UTF8, 0, format->formatName, -1,
lpWideCharStr, cchWideChar) *
2;
if (formatNameSize < 0)
return NULL;
Stream_Seek(s, (size_t)formatNameSize);
}
else
{
Stream_Write_UINT16(s, 0);
}
}
}
return s;
}
UINT cliprdr_read_unlock_clipdata(wStream* s, CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData)
{
if (Stream_GetRemainingLength(s) < 4)
{
WLog_ERR(TAG, "not enough remaining data");
return ERROR_INVALID_DATA;
}
Stream_Read_UINT32(s, unlockClipboardData->clipDataId); /* clipDataId (4 bytes) */
return CHANNEL_RC_OK;
}
UINT cliprdr_read_format_data_request(wStream* s, CLIPRDR_FORMAT_DATA_REQUEST* request)
{
if (Stream_GetRemainingLength(s) < 4)
{
WLog_ERR(TAG, "not enough data in stream!");
return ERROR_INVALID_DATA;
}
Stream_Read_UINT32(s, request->requestedFormatId); /* requestedFormatId (4 bytes) */
return CHANNEL_RC_OK;
}
UINT cliprdr_read_format_data_response(wStream* s, CLIPRDR_FORMAT_DATA_RESPONSE* response)
{
response->requestedFormatData = NULL;
if (Stream_GetRemainingLength(s) < response->dataLen)
{
WLog_ERR(TAG, "not enough data in stream!");
return ERROR_INVALID_DATA;
}
if (response->dataLen)
response->requestedFormatData = Stream_Pointer(s);
return CHANNEL_RC_OK;
}
UINT cliprdr_read_file_contents_request(wStream* s, CLIPRDR_FILE_CONTENTS_REQUEST* request)
{
if (Stream_GetRemainingLength(s) < 24)
{
WLog_ERR(TAG, "not enough remaining data");
return ERROR_INVALID_DATA;
}
request->haveClipDataId = FALSE;
Stream_Read_UINT32(s, request->streamId); /* streamId (4 bytes) */
Stream_Read_UINT32(s, request->listIndex); /* listIndex (4 bytes) */
Stream_Read_UINT32(s, request->dwFlags); /* dwFlags (4 bytes) */
Stream_Read_UINT32(s, request->nPositionLow); /* nPositionLow (4 bytes) */
Stream_Read_UINT32(s, request->nPositionHigh); /* nPositionHigh (4 bytes) */
Stream_Read_UINT32(s, request->cbRequested); /* cbRequested (4 bytes) */
if (Stream_GetRemainingLength(s) >= 4)
{
Stream_Read_UINT32(s, request->clipDataId); /* clipDataId (4 bytes) */
request->haveClipDataId = TRUE;
}
if (!cliprdr_validate_file_contents_request(request))
return ERROR_BAD_ARGUMENTS;
return CHANNEL_RC_OK;
}
UINT cliprdr_read_file_contents_response(wStream* s, CLIPRDR_FILE_CONTENTS_RESPONSE* response)
{
if (Stream_GetRemainingLength(s) < 4)
{
WLog_ERR(TAG, "not enough remaining data");
return ERROR_INVALID_DATA;
}
Stream_Read_UINT32(s, response->streamId); /* streamId (4 bytes) */
response->requestedData = Stream_Pointer(s); /* requestedFileContentsData */
response->cbRequested = response->dataLen - 4;
return CHANNEL_RC_OK;
}
UINT cliprdr_read_format_list(wStream* s, CLIPRDR_FORMAT_LIST* formatList, BOOL useLongFormatNames)
{
UINT32 index;
size_t position;
BOOL asciiNames;
int formatNameLength;
char* szFormatName;
WCHAR* wszFormatName;
UINT32 dataLen = formatList->dataLen;
CLIPRDR_FORMAT* formats = NULL;
UINT error = CHANNEL_RC_OK;
asciiNames = (formatList->msgFlags & CB_ASCII_NAMES) ? TRUE : FALSE;
index = 0;
formatList->numFormats = 0;
position = Stream_GetPosition(s);
if (!formatList->dataLen)
{
/* empty format list */
formatList->formats = NULL;
formatList->numFormats = 0;
}
else if (!useLongFormatNames)
{
formatList->numFormats = (dataLen / 36);
if ((formatList->numFormats * 36) != dataLen)
{
WLog_ERR(TAG, "Invalid short format list length: %" PRIu32 "", dataLen);
return ERROR_INTERNAL_ERROR;
}
if (formatList->numFormats)
formats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));
if (!formats)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
formatList->formats = formats;
while (dataLen)
{
Stream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */
dataLen -= 4;
formats[index].formatName = NULL;
/* According to MS-RDPECLIP 2.2.3.1.1.1 formatName is "a 32-byte block containing
* the *null-terminated* name assigned to the Clipboard Format: (32 ASCII 8 characters
* or 16 Unicode characters)"
* However, both Windows RDSH and mstsc violate this specs as seen in the following
* example of a transferred short format name string: [R.i.c.h. .T.e.x.t. .F.o.r.m.a.t.]
* These are 16 unicode charaters - *without* terminating null !
*/
if (asciiNames)
{
szFormatName = (char*)Stream_Pointer(s);
if (szFormatName[0])
{
/* ensure null termination */
formats[index].formatName = (char*)malloc(32 + 1);
if (!formats[index].formatName)
{
WLog_ERR(TAG, "malloc failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
CopyMemory(formats[index].formatName, szFormatName, 32);
formats[index].formatName[32] = '\0';
}
}
else
{
wszFormatName = (WCHAR*)Stream_Pointer(s);
if (wszFormatName[0])
{
/* ConvertFromUnicode always returns a null-terminated
* string on success, even if the source string isn't.
*/
if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, 16,
&(formats[index].formatName), 0, NULL, NULL) < 1)
{
WLog_ERR(TAG, "failed to convert short clipboard format name");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
}
}
Stream_Seek(s, 32);
dataLen -= 32;
index++;
}
}
else
{
while (dataLen)
{
Stream_Seek(s, 4); /* formatId (4 bytes) */
dataLen -= 4;
wszFormatName = (WCHAR*)Stream_Pointer(s);
if (!wszFormatName[0])
formatNameLength = 0;
else
formatNameLength = _wcslen(wszFormatName);
Stream_Seek(s, (formatNameLength + 1) * 2);
dataLen -= ((formatNameLength + 1) * 2);
formatList->numFormats++;
}
dataLen = formatList->dataLen;
Stream_SetPosition(s, position);
if (formatList->numFormats)
formats = (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT));
if (!formats)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
formatList->formats = formats;
while (dataLen)
{
Stream_Read_UINT32(s, formats[index].formatId); /* formatId (4 bytes) */
dataLen -= 4;
formats[index].formatName = NULL;
wszFormatName = (WCHAR*)Stream_Pointer(s);
if (!wszFormatName[0])
formatNameLength = 0;
else
formatNameLength = _wcslen(wszFormatName);
if (formatNameLength)
{
if (ConvertFromUnicode(CP_UTF8, 0, wszFormatName, -1, &(formats[index].formatName),
0, NULL, NULL) < 1)
{
WLog_ERR(TAG, "failed to convert long clipboard format name");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
}
Stream_Seek(s, (formatNameLength + 1) * 2);
dataLen -= ((formatNameLength + 1) * 2);
index++;
}
}
return error;
error_out:
cliprdr_free_format_list(formatList);
return error;
}
void cliprdr_free_format_list(CLIPRDR_FORMAT_LIST* formatList)
{
UINT index = 0;
if (formatList == NULL)
return;
if (formatList->formats)
{
for (index = 0; index < formatList->numFormats; index++)
{
free(formatList->formats[index].formatName);
}
free(formatList->formats);
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3942_0 |
crossvul-cpp_data_good_2667_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 (len - (tptr - pptr) > 0) {
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 (len - (tptr - pptr) > 0) {
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;
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_TCHECK2(tptr[0], 5);
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_2667_0 |
crossvul-cpp_data_good_5300_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/good_5300_0 |
crossvul-cpp_data_good_2649_0 | /*
* Copyright (c) 1998-2004 Hannes Gredler <hannes@gredler.at>
* 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.
*/
/* \summary: Enhanced Interior Gateway Routing Protocol (EIGRP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
/*
* packet format documented at
* http://www.rhyshaden.com/eigrp.htm
* RFC 7868
*/
struct eigrp_common_header {
uint8_t version;
uint8_t opcode;
uint8_t checksum[2];
uint8_t flags[4];
uint8_t seq[4];
uint8_t ack[4];
uint8_t asn[4];
};
#define EIGRP_VERSION 2
#define EIGRP_OPCODE_UPDATE 1
#define EIGRP_OPCODE_QUERY 3
#define EIGRP_OPCODE_REPLY 4
#define EIGRP_OPCODE_HELLO 5
#define EIGRP_OPCODE_IPXSAP 6
#define EIGRP_OPCODE_PROBE 7
static const struct tok eigrp_opcode_values[] = {
{ EIGRP_OPCODE_UPDATE, "Update" },
{ EIGRP_OPCODE_QUERY, "Query" },
{ EIGRP_OPCODE_REPLY, "Reply" },
{ EIGRP_OPCODE_HELLO, "Hello" },
{ EIGRP_OPCODE_IPXSAP, "IPX SAP" },
{ EIGRP_OPCODE_PROBE, "Probe" },
{ 0, NULL}
};
static const struct tok eigrp_common_header_flag_values[] = {
{ 0x01, "Init" },
{ 0x02, "Conditionally Received" },
{ 0, NULL}
};
struct eigrp_tlv_header {
uint8_t type[2];
uint8_t length[2];
};
#define EIGRP_TLV_GENERAL_PARM 0x0001
#define EIGRP_TLV_AUTH 0x0002
#define EIGRP_TLV_SEQ 0x0003
#define EIGRP_TLV_SW_VERSION 0x0004
#define EIGRP_TLV_MCAST_SEQ 0x0005
#define EIGRP_TLV_IP_INT 0x0102
#define EIGRP_TLV_IP_EXT 0x0103
#define EIGRP_TLV_AT_INT 0x0202
#define EIGRP_TLV_AT_EXT 0x0203
#define EIGRP_TLV_AT_CABLE_SETUP 0x0204
#define EIGRP_TLV_IPX_INT 0x0302
#define EIGRP_TLV_IPX_EXT 0x0303
static const struct tok eigrp_tlv_values[] = {
{ EIGRP_TLV_GENERAL_PARM, "General Parameters"},
{ EIGRP_TLV_AUTH, "Authentication"},
{ EIGRP_TLV_SEQ, "Sequence"},
{ EIGRP_TLV_SW_VERSION, "Software Version"},
{ EIGRP_TLV_MCAST_SEQ, "Next Multicast Sequence"},
{ EIGRP_TLV_IP_INT, "IP Internal routes"},
{ EIGRP_TLV_IP_EXT, "IP External routes"},
{ EIGRP_TLV_AT_INT, "AppleTalk Internal routes"},
{ EIGRP_TLV_AT_EXT, "AppleTalk External routes"},
{ EIGRP_TLV_AT_CABLE_SETUP, "AppleTalk Cable setup"},
{ EIGRP_TLV_IPX_INT, "IPX Internal routes"},
{ EIGRP_TLV_IPX_EXT, "IPX External routes"},
{ 0, NULL}
};
struct eigrp_tlv_general_parm_t {
uint8_t k1;
uint8_t k2;
uint8_t k3;
uint8_t k4;
uint8_t k5;
uint8_t res;
uint8_t holdtime[2];
};
struct eigrp_tlv_sw_version_t {
uint8_t ios_major;
uint8_t ios_minor;
uint8_t eigrp_major;
uint8_t eigrp_minor;
};
struct eigrp_tlv_ip_int_t {
uint8_t nexthop[4];
uint8_t delay[4];
uint8_t bandwidth[4];
uint8_t mtu[3];
uint8_t hopcount;
uint8_t reliability;
uint8_t load;
uint8_t reserved[2];
uint8_t plen;
uint8_t destination; /* variable length [1-4] bytes encoding */
};
struct eigrp_tlv_ip_ext_t {
uint8_t nexthop[4];
uint8_t origin_router[4];
uint8_t origin_as[4];
uint8_t tag[4];
uint8_t metric[4];
uint8_t reserved[2];
uint8_t proto_id;
uint8_t flags;
uint8_t delay[4];
uint8_t bandwidth[4];
uint8_t mtu[3];
uint8_t hopcount;
uint8_t reliability;
uint8_t load;
uint8_t reserved2[2];
uint8_t plen;
uint8_t destination; /* variable length [1-4] bytes encoding */
};
struct eigrp_tlv_at_cable_setup_t {
uint8_t cable_start[2];
uint8_t cable_end[2];
uint8_t router_id[4];
};
struct eigrp_tlv_at_int_t {
uint8_t nexthop[4];
uint8_t delay[4];
uint8_t bandwidth[4];
uint8_t mtu[3];
uint8_t hopcount;
uint8_t reliability;
uint8_t load;
uint8_t reserved[2];
uint8_t cable_start[2];
uint8_t cable_end[2];
};
struct eigrp_tlv_at_ext_t {
uint8_t nexthop[4];
uint8_t origin_router[4];
uint8_t origin_as[4];
uint8_t tag[4];
uint8_t proto_id;
uint8_t flags;
uint8_t metric[2];
uint8_t delay[4];
uint8_t bandwidth[4];
uint8_t mtu[3];
uint8_t hopcount;
uint8_t reliability;
uint8_t load;
uint8_t reserved2[2];
uint8_t cable_start[2];
uint8_t cable_end[2];
};
static const struct tok eigrp_ext_proto_id_values[] = {
{ 0x01, "IGRP" },
{ 0x02, "EIGRP" },
{ 0x03, "Static" },
{ 0x04, "RIP" },
{ 0x05, "Hello" },
{ 0x06, "OSPF" },
{ 0x07, "IS-IS" },
{ 0x08, "EGP" },
{ 0x09, "BGP" },
{ 0x0a, "IDRP" },
{ 0x0b, "Connected" },
{ 0, NULL}
};
void
eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct eigrp_common_header *eigrp_com_header;
const struct eigrp_tlv_header *eigrp_tlv_header;
const u_char *tptr,*tlv_tptr;
u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length;
uint8_t prefix[4];
union {
const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm;
const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version;
const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int;
const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext;
const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup;
const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int;
const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext;
} tlv_ptr;
tptr=pptr;
eigrp_com_header = (const struct eigrp_common_header *)pptr;
ND_TCHECK(*eigrp_com_header);
/*
* Sanity checking of the header.
*/
if (eigrp_com_header->version != EIGRP_VERSION) {
ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "EIGRP %s, length: %u",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
if (len < sizeof(struct eigrp_common_header)) {
ND_PRINT((ndo, "EIGRP %s, length: %u (too short, < %u)",
tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode),
len, (u_int) sizeof(struct eigrp_common_header)));
return;
}
tlen=len-sizeof(struct eigrp_common_header);
/* FIXME print other header info */
ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u",
eigrp_com_header->version,
tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode),
eigrp_com_header->opcode,
EXTRACT_16BITS(&eigrp_com_header->checksum),
tok2str(eigrp_common_header_flag_values,
"none",
EXTRACT_32BITS(&eigrp_com_header->flags)),
EXTRACT_32BITS(&eigrp_com_header->seq),
EXTRACT_32BITS(&eigrp_com_header->ack),
EXTRACT_32BITS(&eigrp_com_header->asn),
tlen));
tptr+=sizeof(const struct eigrp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header));
eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr;
eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length);
eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type);
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) ||
eigrp_tlv_len > tlen) {
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen);
return;
}
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u",
tok2str(eigrp_tlv_values,
"Unknown",
eigrp_tlv_type),
eigrp_tlv_type,
eigrp_tlv_len));
if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) sizeof(struct eigrp_tlv_header)));
break;
}
tlv_tptr=tptr+sizeof(struct eigrp_tlv_header);
tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, eigrp_tlv_len);
switch(eigrp_tlv_type) {
case EIGRP_TLV_GENERAL_PARM:
tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_general_parm)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_general_parm))));
break;
}
ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u",
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime),
tlv_ptr.eigrp_tlv_general_parm->k1,
tlv_ptr.eigrp_tlv_general_parm->k2,
tlv_ptr.eigrp_tlv_general_parm->k3,
tlv_ptr.eigrp_tlv_general_parm->k4,
tlv_ptr.eigrp_tlv_general_parm->k5));
break;
case EIGRP_TLV_SW_VERSION:
tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_sw_version)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_sw_version))));
break;
}
ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u",
tlv_ptr.eigrp_tlv_sw_version->ios_major,
tlv_ptr.eigrp_tlv_sw_version->ios_minor,
tlv_ptr.eigrp_tlv_sw_version->eigrp_major,
tlv_ptr.eigrp_tlv_sw_version->eigrp_minor));
break;
case EIGRP_TLV_IP_INT:
tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_ip_int)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_ip_int))));
break;
}
bit_length = tlv_ptr.eigrp_tlv_ip_int->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu),
tlv_ptr.eigrp_tlv_ip_int->hopcount,
tlv_ptr.eigrp_tlv_ip_int->reliability,
tlv_ptr.eigrp_tlv_ip_int->load));
break;
case EIGRP_TLV_IP_EXT:
tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_ip_ext)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_ip_ext))));
break;
}
bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen;
if (bit_length > 32) {
ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length));
break;
}
byte_length = (bit_length + 7) / 8; /* variable length encoding */
memset(prefix, 0, 4);
memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length);
ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ",
ipaddr_string(ndo, prefix),
bit_length));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop)));
ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id),
tlv_ptr.eigrp_tlv_ip_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu),
tlv_ptr.eigrp_tlv_ip_ext->hopcount,
tlv_ptr.eigrp_tlv_ip_ext->reliability,
tlv_ptr.eigrp_tlv_ip_ext->load));
break;
case EIGRP_TLV_AT_CABLE_SETUP:
tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_cable_setup)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_cable_setup))));
break;
}
ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id)));
break;
case EIGRP_TLV_AT_INT:
tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_int)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_int))));
break;
}
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2])));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu),
tlv_ptr.eigrp_tlv_at_int->hopcount,
tlv_ptr.eigrp_tlv_at_int->reliability,
tlv_ptr.eigrp_tlv_at_int->load));
break;
case EIGRP_TLV_AT_EXT:
tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr;
if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_ext)) {
ND_PRINT((ndo, " (too short, < %u)",
(u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_ext))));
break;
}
ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end)));
if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0)
ND_PRINT((ndo, "self"));
else
ND_PRINT((ndo, "%u.%u",
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop),
EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2])));
ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u",
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router),
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as),
tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id),
tlv_ptr.eigrp_tlv_at_ext->flags,
EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag),
EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric)));
ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u",
(EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100),
EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth),
EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu),
tlv_ptr.eigrp_tlv_at_ext->hopcount,
tlv_ptr.eigrp_tlv_at_ext->reliability,
tlv_ptr.eigrp_tlv_at_ext->load));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case EIGRP_TLV_AUTH:
case EIGRP_TLV_SEQ:
case EIGRP_TLV_MCAST_SEQ:
case EIGRP_TLV_IPX_INT:
case EIGRP_TLV_IPX_EXT:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",
eigrp_tlv_len-sizeof(struct eigrp_tlv_header));
tptr+=eigrp_tlv_len;
tlen-=eigrp_tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2649_0 |
crossvul-cpp_data_bad_4019_3 | /* exif-mnote-data-pentax.c
*
* Copyright (c) 2002, 2003 Lutz Mueller <lutz@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "exif-mnote-data-pentax.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <libexif/exif-byte-order.h>
#include <libexif/exif-utils.h>
static void
exif_mnote_data_pentax_clear (ExifMnoteDataPentax *n)
{
ExifMnoteData *d = (ExifMnoteData *) n;
unsigned int i;
if (!n) return;
if (n->entries) {
for (i = 0; i < n->count; i++)
if (n->entries[i].data) {
exif_mem_free (d->mem, n->entries[i].data);
n->entries[i].data = NULL;
}
exif_mem_free (d->mem, n->entries);
n->entries = NULL;
n->count = 0;
}
}
static void
exif_mnote_data_pentax_free (ExifMnoteData *n)
{
if (!n) return;
exif_mnote_data_pentax_clear ((ExifMnoteDataPentax *) n);
}
static char *
exif_mnote_data_pentax_get_value (ExifMnoteData *d, unsigned int i, char *val, unsigned int maxlen)
{
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) d;
if (!n) return NULL;
if (n->count <= i) return NULL;
return mnote_pentax_entry_get_value (&n->entries[i], val, maxlen);
}
/**
* @brief save the MnoteData from ne to buf
*
* @param ne extract the data from this structure
* @param *buf write the mnoteData to this buffer (buffer will be allocated)
* @param buf_size the final size of the buffer
*/
static void
exif_mnote_data_pentax_save (ExifMnoteData *ne,
unsigned char **buf, unsigned int *buf_size)
{
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) ne;
size_t i, datao,
base = 0, /* internal MakerNote tag number offset */
o2 = 4 + 2; /* offset to first tag entry, past header */
if (!n || !buf || !buf_size) return;
datao = n->offset; /* this MakerNote style uses offsets
based on main IFD, not makernote IFD */
/*
* Allocate enough memory for header, the number of entries, entries,
* and next IFD pointer
*/
*buf_size = o2 + 2 + n->count * 12 + 4;
switch (n->version) {
case casioV2:
base = MNOTE_PENTAX2_TAG_BASE;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
/* Write the magic header */
strcpy ((char *)*buf, "QVC");
exif_set_short (*buf + 4, n->order, (ExifShort) 0);
break;
case pentaxV3:
base = MNOTE_PENTAX2_TAG_BASE;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
/* Write the magic header */
strcpy ((char *)*buf, "AOC");
exif_set_short (*buf + 4, n->order, (ExifShort) (
(n->order == EXIF_BYTE_ORDER_INTEL) ?
('I' << 8) | 'I' :
('M' << 8) | 'M'));
break;
case pentaxV2:
base = MNOTE_PENTAX2_TAG_BASE;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
/* Write the magic header */
strcpy ((char *)*buf, "AOC");
exif_set_short (*buf + 4, n->order, (ExifShort) 0);
break;
case pentaxV1:
/* It looks like this format doesn't have a magic header as
* such, just has a fixed number of entries equal to 0x001b */
*buf_size -= 6;
o2 -= 6;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
break;
default:
/* internal error */
return;
}
/* Write the number of entries. */
exif_set_short (*buf + o2, n->order, (ExifShort) n->count);
o2 += 2;
/* Save each entry */
for (i = 0; i < n->count; i++) {
size_t doff; /* offset to current data portion of tag */
size_t s;
unsigned char *t;
size_t o = o2 + i * 12; /* current offset into output buffer */
exif_set_short (*buf + o + 0, n->order,
(ExifShort) (n->entries[i].tag - base));
exif_set_short (*buf + o + 2, n->order,
(ExifShort) n->entries[i].format);
exif_set_long (*buf + o + 4, n->order,
n->entries[i].components);
o += 8;
s = exif_format_get_size (n->entries[i].format) *
n->entries[i].components;
if (s > 65536) {
/* Corrupt data: EXIF data size is limited to the
* maximum size of a JPEG segment (64 kb).
*/
continue;
}
if (s > 4) {
size_t ts = *buf_size + s;
doff = *buf_size;
t = exif_mem_realloc (ne->mem, *buf,
sizeof (char) * ts);
if (!t) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", ts);
return;
}
*buf = t;
*buf_size = ts;
exif_set_long (*buf + o, n->order, datao + doff);
} else
doff = o;
/* Write the data. */
if (n->entries[i].data) {
memcpy (*buf + doff, n->entries[i].data, s);
} else {
/* Most certainly damaged input file */
memset (*buf + doff, 0, s);
}
}
/* Sanity check the buffer size */
if (*buf_size < (o2 + n->count * 12 + 4)) {
exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataPentax",
"Buffer overflow");
}
/* Reset next IFD pointer */
exif_set_long (*buf + o2 + n->count * 12, n->order, 0);
}
static void
exif_mnote_data_pentax_load (ExifMnoteData *en,
const unsigned char *buf, unsigned int buf_size)
{
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) en;
size_t i, tcount, o, datao, base = 0;
ExifShort c;
if (!n || !buf || !buf_size) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Short MakerNote");
return;
}
datao = 6 + n->offset;
if ((datao + 8 < datao) || (datao + 8 < 8) || (datao + 8 > buf_size)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Short MakerNote");
return;
}
/* Detect variant of Pentax/Casio MakerNote found */
if (!memcmp(buf + datao, "AOC", 4)) {
if ((buf[datao + 4] == 'I') && (buf[datao + 5] == 'I')) {
n->version = pentaxV3;
n->order = EXIF_BYTE_ORDER_INTEL;
} else if ((buf[datao + 4] == 'M') && (buf[datao + 5] == 'M')) {
n->version = pentaxV3;
n->order = EXIF_BYTE_ORDER_MOTOROLA;
} else {
/* Uses Casio v2 tags */
n->version = pentaxV2;
}
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax",
"Parsing Pentax maker note v%d...", (int)n->version);
datao += 4 + 2;
base = MNOTE_PENTAX2_TAG_BASE;
} else if (!memcmp(buf + datao, "QVC", 4)) {
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax",
"Parsing Casio maker note v2...");
n->version = casioV2;
base = MNOTE_CASIO2_TAG_BASE;
datao += 4 + 2;
} else {
/* probably assert(!memcmp(buf + datao, "\x00\x1b", 2)) */
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax",
"Parsing Pentax maker note v1...");
n->version = pentaxV1;
}
/* Read the number of tags */
c = exif_get_short (buf + datao, n->order);
datao += 2;
/* Remove any old entries */
exif_mnote_data_pentax_clear (n);
/* Reserve enough space for all the possible MakerNote tags */
n->entries = exif_mem_alloc (en->mem, sizeof (MnotePentaxEntry) * c);
if (!n->entries) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataPentax", sizeof (MnotePentaxEntry) * c);
return;
}
/* Parse all c entries, storing ones that are successfully parsed */
tcount = 0;
for (i = c, o = datao; i; --i, o += 12) {
size_t s;
if ((o + 12 < o) || (o + 12 < 12) || (o + 12 > buf_size)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Short MakerNote");
break;
}
n->entries[tcount].tag = exif_get_short (buf + o + 0, n->order) + base;
n->entries[tcount].format = exif_get_short (buf + o + 2, n->order);
n->entries[tcount].components = exif_get_long (buf + o + 4, n->order);
n->entries[tcount].order = n->order;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnotePentax",
"Loading entry 0x%x ('%s')...", n->entries[tcount].tag,
mnote_pentax_tag_get_name (n->entries[tcount].tag));
/*
* Size? If bigger than 4 bytes, the actual data is not
* in the entry but somewhere else (offset).
*/
s = exif_format_get_size (n->entries[tcount].format) *
n->entries[tcount].components;
n->entries[tcount].size = s;
if (s) {
size_t dataofs = o + 8;
if (s > 4)
/* The data in this case is merely a pointer */
dataofs = exif_get_long (buf + dataofs, n->order) + 6;
if ((dataofs + s < dataofs) || (dataofs + s < s) ||
(dataofs + s > buf_size)) {
exif_log (en->log, EXIF_LOG_CODE_DEBUG,
"ExifMnoteDataPentax", "Tag data past end "
"of buffer (%u > %u)", (unsigned)(dataofs + s), buf_size);
continue;
}
n->entries[tcount].data = exif_mem_alloc (en->mem, s);
if (!n->entries[tcount].data) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataPentax", s);
continue;
}
memcpy (n->entries[tcount].data, buf + dataofs, s);
}
/* Tag was successfully parsed */
++tcount;
}
/* Store the count of successfully parsed tags */
n->count = tcount;
}
static unsigned int
exif_mnote_data_pentax_count (ExifMnoteData *n)
{
return n ? ((ExifMnoteDataPentax *) n)->count : 0;
}
static unsigned int
exif_mnote_data_pentax_get_id (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return 0;
if (note->count <= n) return 0;
return note->entries[n].tag;
}
static const char *
exif_mnote_data_pentax_get_name (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return NULL;
if (note->count <= n) return NULL;
return mnote_pentax_tag_get_name (note->entries[n].tag);
}
static const char *
exif_mnote_data_pentax_get_title (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return NULL;
if (note->count <= n) return NULL;
return mnote_pentax_tag_get_title (note->entries[n].tag);
}
static const char *
exif_mnote_data_pentax_get_description (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return NULL;
if (note->count <= n) return NULL;
return mnote_pentax_tag_get_description (note->entries[n].tag);
}
static void
exif_mnote_data_pentax_set_offset (ExifMnoteData *d, unsigned int o)
{
if (d) ((ExifMnoteDataPentax *) d)->offset = o;
}
static void
exif_mnote_data_pentax_set_byte_order (ExifMnoteData *d, ExifByteOrder o)
{
ExifByteOrder o_orig;
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) d;
unsigned int i;
if (!n) return;
o_orig = n->order;
n->order = o;
for (i = 0; i < n->count; i++) {
if (n->entries[i].components && (n->entries[i].size/n->entries[i].components < exif_format_get_size (n->entries[i].format)))
continue;
n->entries[i].order = o;
exif_array_set_byte_order (n->entries[i].format, n->entries[i].data,
n->entries[i].components, o_orig, o);
}
}
int
exif_mnote_data_pentax_identify (const ExifData *ed, const ExifEntry *e)
{
(void) ed; /* unused */
if ((e->size >= 8) && !memcmp (e->data, "AOC", 4)) {
if (((e->data[4] == 'I') && (e->data[5] == 'I')) ||
((e->data[4] == 'M') && (e->data[5] == 'M')))
return pentaxV3;
else
/* Uses Casio v2 tags */
return pentaxV2;
}
if ((e->size >= 8) && !memcmp (e->data, "QVC", 4))
return casioV2;
/* This isn't a very robust test, so make sure it's done last */
/* Maybe we should additionally check for a make of Asahi or Pentax */
if ((e->size >= 2) && (e->data[0] == 0x00) && (e->data[1] == 0x1b))
return pentaxV1;
return 0;
}
ExifMnoteData *
exif_mnote_data_pentax_new (ExifMem *mem)
{
ExifMnoteData *d;
if (!mem) return NULL;
d = exif_mem_alloc (mem, sizeof (ExifMnoteDataPentax));
if (!d) return NULL;
exif_mnote_data_construct (d, mem);
/* Set up function pointers */
d->methods.free = exif_mnote_data_pentax_free;
d->methods.set_byte_order = exif_mnote_data_pentax_set_byte_order;
d->methods.set_offset = exif_mnote_data_pentax_set_offset;
d->methods.load = exif_mnote_data_pentax_load;
d->methods.save = exif_mnote_data_pentax_save;
d->methods.count = exif_mnote_data_pentax_count;
d->methods.get_id = exif_mnote_data_pentax_get_id;
d->methods.get_name = exif_mnote_data_pentax_get_name;
d->methods.get_title = exif_mnote_data_pentax_get_title;
d->methods.get_description = exif_mnote_data_pentax_get_description;
d->methods.get_value = exif_mnote_data_pentax_get_value;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4019_3 |
crossvul-cpp_data_good_4840_0 | /* Copyright 2006-2007 Niels Provos
* Copyright 2007-2012 Nick Mathewson and Niels Provos
*
* 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 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 software by Adam Langly. Adam's original message:
*
* Async DNS Library
* Adam Langley <agl@imperialviolet.org>
* http://www.imperialviolet.org/eventdns.html
* Public Domain code
*
* This software is Public Domain. To view a copy of the public domain dedication,
* visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
* Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
*
* I ask and expect, but do not require, that all derivative works contain an
* attribution similar to:
* Parts developed by Adam Langley <agl@imperialviolet.org>
*
* You may wish to replace the word "Parts" with something else depending on
* the amount of original code.
*
* (Derivative works does not include programs which link against, run or include
* the source verbatim in their source distributions)
*
* Version: 0.1b
*/
#include "event2/event-config.h"
#include "evconfig-private.h"
#include <sys/types.h>
#ifndef _FORTIFY_SOURCE
#define _FORTIFY_SOURCE 3
#endif
#include <string.h>
#include <fcntl.h>
#ifdef EVENT__HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef EVENT__HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifdef EVENT__HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <limits.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdarg.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#ifndef _WIN32_IE
#define _WIN32_IE 0x400
#endif
#include <shlobj.h>
#endif
#include "event2/dns.h"
#include "event2/dns_struct.h"
#include "event2/dns_compat.h"
#include "event2/util.h"
#include "event2/event.h"
#include "event2/event_struct.h"
#include "event2/thread.h"
#include "defer-internal.h"
#include "log-internal.h"
#include "mm-internal.h"
#include "strlcpy-internal.h"
#include "ipv6-internal.h"
#include "util-internal.h"
#include "evthread-internal.h"
#ifdef _WIN32
#include <ctype.h>
#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
#include <io.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef EVENT__HAVE_NETINET_IN6_H
#include <netinet/in6.h>
#endif
#define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
#define EVDNS_LOG_WARN EVENT_LOG_WARN
#define EVDNS_LOG_MSG EVENT_LOG_MSG
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif
#include <stdio.h>
#undef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#define ASSERT_VALID_REQUEST(req) \
EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
#define u64 ev_uint64_t
#define u32 ev_uint32_t
#define u16 ev_uint16_t
#define u8 ev_uint8_t
/* maximum number of addresses from a single packet */
/* that we bother recording */
#define MAX_V4_ADDRS 32
#define MAX_V6_ADDRS 32
#define TYPE_A EVDNS_TYPE_A
#define TYPE_CNAME 5
#define TYPE_PTR EVDNS_TYPE_PTR
#define TYPE_SOA EVDNS_TYPE_SOA
#define TYPE_AAAA EVDNS_TYPE_AAAA
#define CLASS_INET EVDNS_CLASS_INET
/* Persistent handle. We keep this separate from 'struct request' since we
* need some object to last for as long as an evdns_request is outstanding so
* that it can be canceled, whereas a search request can lead to multiple
* 'struct request' instances being created over its lifetime. */
struct evdns_request {
struct request *current_req;
struct evdns_base *base;
int pending_cb; /* Waiting for its callback to be invoked; not
* owned by event base any more. */
/* elements used by the searching code */
int search_index;
struct search_state *search_state;
char *search_origname; /* needs to be free()ed */
int search_flags;
};
struct request {
u8 *request; /* the dns packet data */
u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
unsigned int request_len;
int reissue_count;
int tx_count; /* the number of times that this packet has been sent */
void *user_pointer; /* the pointer given to us for this request */
evdns_callback_type user_callback;
struct nameserver *ns; /* the server which we last sent it */
/* these objects are kept in a circular list */
/* XXX We could turn this into a CIRCLEQ. */
struct request *next, *prev;
struct event timeout_event;
u16 trans_id; /* the transaction id */
unsigned request_appended :1; /* true if the request pointer is data which follows this struct */
unsigned transmit_me :1; /* needs to be transmitted */
/* XXXX This is a horrible hack. */
char **put_cname_in_ptr; /* store the cname here if we get one. */
struct evdns_base *base;
struct evdns_request *handle;
};
struct reply {
unsigned int type;
unsigned int have_answer : 1;
union {
struct {
u32 addrcount;
u32 addresses[MAX_V4_ADDRS];
} a;
struct {
u32 addrcount;
struct in6_addr addresses[MAX_V6_ADDRS];
} aaaa;
struct {
char name[HOST_NAME_MAX];
} ptr;
} data;
};
struct nameserver {
evutil_socket_t socket; /* a connected UDP socket */
struct sockaddr_storage address;
ev_socklen_t addrlen;
int failed_times; /* number of times which we have given this server a chance */
int timedout; /* number of times in a row a request has timed out */
struct event event;
/* these objects are kept in a circular list */
struct nameserver *next, *prev;
struct event timeout_event; /* used to keep the timeout for */
/* when we next probe this server. */
/* Valid if state == 0 */
/* Outstanding probe request for this nameserver, if any */
struct evdns_request *probe_request;
char state; /* zero if we think that this server is down */
char choked; /* true if we have an EAGAIN from this server's socket */
char write_waiting; /* true if we are waiting for EV_WRITE events */
struct evdns_base *base;
/* Number of currently inflight requests: used
* to track when we should add/del the event. */
int requests_inflight;
};
/* Represents a local port where we're listening for DNS requests. Right now, */
/* only UDP is supported. */
struct evdns_server_port {
evutil_socket_t socket; /* socket we use to read queries and write replies. */
int refcnt; /* reference count. */
char choked; /* Are we currently blocked from writing? */
char closing; /* Are we trying to close this port, pending writes? */
evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
void *user_data; /* Opaque pointer passed to user_callback */
struct event event; /* Read/write event */
/* circular list of replies that we want to write. */
struct server_request *pending_replies;
struct event_base *event_base;
#ifndef EVENT__DISABLE_THREAD_SUPPORT
void *lock;
#endif
};
/* Represents part of a reply being built. (That is, a single RR.) */
struct server_reply_item {
struct server_reply_item *next; /* next item in sequence. */
char *name; /* name part of the RR */
u16 type; /* The RR type */
u16 class; /* The RR class (usually CLASS_INET) */
u32 ttl; /* The RR TTL */
char is_name; /* True iff data is a label */
u16 datalen; /* Length of data; -1 if data is a label */
void *data; /* The contents of the RR */
};
/* Represents a request that we've received as a DNS server, and holds */
/* the components of the reply as we're constructing it. */
struct server_request {
/* Pointers to the next and previous entries on the list of replies */
/* that we're waiting to write. Only set if we have tried to respond */
/* and gotten EAGAIN. */
struct server_request *next_pending;
struct server_request *prev_pending;
u16 trans_id; /* Transaction id. */
struct evdns_server_port *port; /* Which port received this request on? */
struct sockaddr_storage addr; /* Where to send the response */
ev_socklen_t addrlen; /* length of addr */
int n_answer; /* how many answer RRs have been set? */
int n_authority; /* how many authority RRs have been set? */
int n_additional; /* how many additional RRs have been set? */
struct server_reply_item *answer; /* linked list of answer RRs */
struct server_reply_item *authority; /* linked list of authority RRs */
struct server_reply_item *additional; /* linked list of additional RRs */
/* Constructed response. Only set once we're ready to send a reply. */
/* Once this is set, the RR fields are cleared, and no more should be set. */
char *response;
size_t response_len;
/* Caller-visible fields: flags, questions. */
struct evdns_server_request base;
};
struct evdns_base {
/* An array of n_req_heads circular lists for inflight requests.
* Each inflight request req is in req_heads[req->trans_id % n_req_heads].
*/
struct request **req_heads;
/* A circular list of requests that we're waiting to send, but haven't
* sent yet because there are too many requests inflight */
struct request *req_waiting_head;
/* A circular list of nameservers. */
struct nameserver *server_head;
int n_req_heads;
struct event_base *event_base;
/* The number of good nameservers that we have */
int global_good_nameservers;
/* inflight requests are contained in the req_head list */
/* and are actually going out across the network */
int global_requests_inflight;
/* requests which aren't inflight are in the waiting list */
/* and are counted here */
int global_requests_waiting;
int global_max_requests_inflight;
struct timeval global_timeout; /* 5 seconds by default */
int global_max_reissues; /* a reissue occurs when we get some errors from the server */
int global_max_retransmits; /* number of times we'll retransmit a request which timed out */
/* number of timeouts in a row before we consider this server to be down */
int global_max_nameserver_timeout;
/* true iff we will use the 0x20 hack to prevent poisoning attacks. */
int global_randomize_case;
/* The first time that a nameserver fails, how long do we wait before
* probing to see if it has returned? */
struct timeval global_nameserver_probe_initial_timeout;
/** Port to bind to for outgoing DNS packets. */
struct sockaddr_storage global_outgoing_address;
/** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
ev_socklen_t global_outgoing_addrlen;
struct timeval global_getaddrinfo_allow_skew;
int getaddrinfo_ipv4_timeouts;
int getaddrinfo_ipv6_timeouts;
int getaddrinfo_ipv4_answered;
int getaddrinfo_ipv6_answered;
struct search_state *global_search_state;
TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
#ifndef EVENT__DISABLE_THREAD_SUPPORT
void *lock;
#endif
int disable_when_inactive;
};
struct hosts_entry {
TAILQ_ENTRY(hosts_entry) next;
union {
struct sockaddr sa;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
} addr;
int addrlen;
char hostname[1];
};
static struct evdns_base *current_base = NULL;
struct evdns_base *
evdns_get_global_base(void)
{
return current_base;
}
/* Given a pointer to an evdns_server_request, get the corresponding */
/* server_request. */
#define TO_SERVER_REQUEST(base_ptr) \
((struct server_request*) \
(((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
#define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
static struct nameserver *nameserver_pick(struct evdns_base *base);
static void evdns_request_insert(struct request *req, struct request **head);
static void evdns_request_remove(struct request *req, struct request **head);
static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
static int evdns_transmit(struct evdns_base *base);
static int evdns_request_transmit(struct request *req);
static void nameserver_send_probe(struct nameserver *const ns);
static void search_request_finished(struct evdns_request *const);
static int search_try_next(struct evdns_request *const req);
static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
static u16 transaction_id_pick(struct evdns_base *base);
static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
static void request_submit(struct request *const req);
static int server_request_free(struct server_request *req);
static void server_request_free_answers(struct server_request *req);
static void server_port_free(struct evdns_server_port *port);
static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
static int evdns_base_set_option_impl(struct evdns_base *base,
const char *option, const char *val, int flags);
static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
static void evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg);
static int strtoint(const char *const str);
#ifdef EVENT__DISABLE_THREAD_SUPPORT
#define EVDNS_LOCK(base) EVUTIL_NIL_STMT_
#define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
#define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
#else
#define EVDNS_LOCK(base) \
EVLOCK_LOCK((base)->lock, 0)
#define EVDNS_UNLOCK(base) \
EVLOCK_UNLOCK((base)->lock, 0)
#define ASSERT_LOCKED(base) \
EVLOCK_ASSERT_LOCKED((base)->lock)
#endif
static evdns_debug_log_fn_type evdns_log_fn = NULL;
void
evdns_set_log_fn(evdns_debug_log_fn_type fn)
{
evdns_log_fn = fn;
}
#ifdef __GNUC__
#define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
#else
#define EVDNS_LOG_CHECK
#endif
static void evdns_log_(int severity, const char *fmt, ...) EVDNS_LOG_CHECK;
static void
evdns_log_(int severity, const char *fmt, ...)
{
va_list args;
va_start(args,fmt);
if (evdns_log_fn) {
char buf[512];
int is_warn = (severity == EVDNS_LOG_WARN);
evutil_vsnprintf(buf, sizeof(buf), fmt, args);
evdns_log_fn(is_warn, buf);
} else {
event_logv_(severity, NULL, fmt, args);
}
va_end(args);
}
#define log evdns_log_
/* This walks the list of inflight requests to find the */
/* one with a matching transaction id. Returns NULL on */
/* failure */
static struct request *
request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
struct request *req = REQ_HEAD(base, trans_id);
struct request *const started_at = req;
ASSERT_LOCKED(base);
if (req) {
do {
if (req->trans_id == trans_id) return req;
req = req->next;
} while (req != started_at);
}
return NULL;
}
/* a libevent callback function which is called when a nameserver */
/* has gone down and we want to test if it has came back to life yet */
static void
nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
struct nameserver *const ns = (struct nameserver *) arg;
(void)fd;
(void)events;
EVDNS_LOCK(ns->base);
nameserver_send_probe(ns);
EVDNS_UNLOCK(ns->base);
}
/* a libevent callback which is called when a nameserver probe (to see if */
/* it has come back to life) times out. We increment the count of failed_times */
/* and wait longer to send the next probe packet. */
static void
nameserver_probe_failed(struct nameserver *const ns) {
struct timeval timeout;
int i;
ASSERT_LOCKED(ns->base);
(void) evtimer_del(&ns->timeout_event);
if (ns->state == 1) {
/* This can happen if the nameserver acts in a way which makes us mark */
/* it as bad and then starts sending good replies. */
return;
}
#define MAX_PROBE_TIMEOUT 3600
#define TIMEOUT_BACKOFF_FACTOR 3
memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
sizeof(struct timeval));
for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
if (timeout.tv_usec > 1000000) {
timeout.tv_sec += timeout.tv_usec / 1000000;
timeout.tv_usec %= 1000000;
}
}
if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
timeout.tv_sec = MAX_PROBE_TIMEOUT;
timeout.tv_usec = 0;
}
ns->failed_times++;
if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
char addrbuf[128];
log(EVDNS_LOG_WARN,
"Error from libevent when adding timer event for %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
}
}
static void
request_swap_ns(struct request *req, struct nameserver *ns) {
if (ns && req->ns != ns) {
EVUTIL_ASSERT(req->ns->requests_inflight > 0);
req->ns->requests_inflight--;
ns->requests_inflight++;
req->ns = ns;
}
}
/* called when a nameserver has been deemed to have failed. For example, too */
/* many packets have timed out etc */
static void
nameserver_failed(struct nameserver *const ns, const char *msg) {
struct request *req, *started_at;
struct evdns_base *base = ns->base;
int i;
char addrbuf[128];
ASSERT_LOCKED(base);
/* if this nameserver has already been marked as failed */
/* then don't do anything */
if (!ns->state) return;
log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)),
msg);
base->global_good_nameservers--;
EVUTIL_ASSERT(base->global_good_nameservers >= 0);
if (base->global_good_nameservers == 0) {
log(EVDNS_LOG_MSG, "All nameservers have failed");
}
ns->state = 0;
ns->failed_times = 1;
if (evtimer_add(&ns->timeout_event,
&base->global_nameserver_probe_initial_timeout) < 0) {
log(EVDNS_LOG_WARN,
"Error from libevent when adding timer event for %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
/* ???? Do more? */
}
/* walk the list of inflight requests to see if any can be reassigned to */
/* a different server. Requests in the waiting queue don't have a */
/* nameserver assigned yet */
/* if we don't have *any* good nameservers then there's no point */
/* trying to reassign requests to one */
if (!base->global_good_nameservers) return;
for (i = 0; i < base->n_req_heads; ++i) {
req = started_at = base->req_heads[i];
if (req) {
do {
if (req->tx_count == 0 && req->ns == ns) {
/* still waiting to go out, can be moved */
/* to another server */
request_swap_ns(req, nameserver_pick(base));
}
req = req->next;
} while (req != started_at);
}
}
}
static void
nameserver_up(struct nameserver *const ns)
{
char addrbuf[128];
ASSERT_LOCKED(ns->base);
if (ns->state) return;
log(EVDNS_LOG_MSG, "Nameserver %s is back up",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
evtimer_del(&ns->timeout_event);
if (ns->probe_request) {
evdns_cancel_request(ns->base, ns->probe_request);
ns->probe_request = NULL;
}
ns->state = 1;
ns->failed_times = 0;
ns->timedout = 0;
ns->base->global_good_nameservers++;
}
static void
request_trans_id_set(struct request *const req, const u16 trans_id) {
req->trans_id = trans_id;
*((u16 *) req->request) = htons(trans_id);
}
/* Called to remove a request from a list and dealloc it. */
/* head is a pointer to the head of the list it should be */
/* removed from or NULL if the request isn't in a list. */
/* when free_handle is one, free the handle as well. */
static void
request_finished(struct request *const req, struct request **head, int free_handle) {
struct evdns_base *base = req->base;
int was_inflight = (head != &base->req_waiting_head);
EVDNS_LOCK(base);
ASSERT_VALID_REQUEST(req);
if (head)
evdns_request_remove(req, head);
log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
if (was_inflight) {
evtimer_del(&req->timeout_event);
base->global_requests_inflight--;
req->ns->requests_inflight--;
} else {
base->global_requests_waiting--;
}
/* it was initialized during request_new / evtimer_assign */
event_debug_unassign(&req->timeout_event);
if (req->ns &&
req->ns->requests_inflight == 0 &&
req->base->disable_when_inactive) {
event_del(&req->ns->event);
evtimer_del(&req->ns->timeout_event);
}
if (!req->request_appended) {
/* need to free the request data on it's own */
mm_free(req->request);
} else {
/* the request data is appended onto the header */
/* so everything gets free()ed when we: */
}
if (req->handle) {
EVUTIL_ASSERT(req->handle->current_req == req);
if (free_handle) {
search_request_finished(req->handle);
req->handle->current_req = NULL;
if (! req->handle->pending_cb) {
/* If we're planning to run the callback,
* don't free the handle until later. */
mm_free(req->handle);
}
req->handle = NULL; /* If we have a bug, let's crash
* early */
} else {
req->handle->current_req = NULL;
}
}
mm_free(req);
evdns_requests_pump_waiting_queue(base);
EVDNS_UNLOCK(base);
}
/* This is called when a server returns a funny error code. */
/* We try the request again with another server. */
/* */
/* return: */
/* 0 ok */
/* 1 failed/reissue is pointless */
static int
request_reissue(struct request *req) {
const struct nameserver *const last_ns = req->ns;
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
/* the last nameserver should have been marked as failing */
/* by the caller of this function, therefore pick will try */
/* not to return it */
request_swap_ns(req, nameserver_pick(req->base));
if (req->ns == last_ns) {
/* ... but pick did return it */
/* not a lot of point in trying again with the */
/* same server */
return 1;
}
req->reissue_count++;
req->tx_count = 0;
req->transmit_me = 1;
return 0;
}
/* this function looks for space on the inflight queue and promotes */
/* requests from the waiting queue if it can. */
/* */
/* TODO: */
/* add return code, see at nameserver_pick() and other functions. */
static void
evdns_requests_pump_waiting_queue(struct evdns_base *base) {
ASSERT_LOCKED(base);
while (base->global_requests_inflight < base->global_max_requests_inflight &&
base->global_requests_waiting) {
struct request *req;
EVUTIL_ASSERT(base->req_waiting_head);
req = base->req_waiting_head;
req->ns = nameserver_pick(base);
if (!req->ns)
return;
/* move a request from the waiting queue to the inflight queue */
req->ns->requests_inflight++;
evdns_request_remove(req, &base->req_waiting_head);
base->global_requests_waiting--;
base->global_requests_inflight++;
request_trans_id_set(req, transaction_id_pick(base));
evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
evdns_request_transmit(req);
evdns_transmit(base);
}
}
/* TODO(nickm) document */
struct deferred_reply_callback {
struct event_callback deferred;
struct evdns_request *handle;
u8 request_type;
u8 have_reply;
u32 ttl;
u32 err;
evdns_callback_type user_callback;
struct reply reply;
};
static void
reply_run_callback(struct event_callback *d, void *user_pointer)
{
struct deferred_reply_callback *cb =
EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
switch (cb->request_type) {
case TYPE_A:
if (cb->have_reply)
cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
cb->reply.data.a.addrcount, cb->ttl,
cb->reply.data.a.addresses,
user_pointer);
else
cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
break;
case TYPE_PTR:
if (cb->have_reply) {
char *name = cb->reply.data.ptr.name;
cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
&name, user_pointer);
} else {
cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
}
break;
case TYPE_AAAA:
if (cb->have_reply)
cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
cb->reply.data.aaaa.addrcount, cb->ttl,
cb->reply.data.aaaa.addresses,
user_pointer);
else
cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
break;
default:
EVUTIL_ASSERT(0);
}
if (cb->handle && cb->handle->pending_cb) {
mm_free(cb->handle);
}
mm_free(cb);
}
static void
reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
{
struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
if (!d) {
event_warn("%s: Couldn't allocate space for deferred callback.",
__func__);
return;
}
ASSERT_LOCKED(req->base);
d->request_type = req->request_type;
d->user_callback = req->user_callback;
d->ttl = ttl;
d->err = err;
if (reply) {
d->have_reply = 1;
memcpy(&d->reply, reply, sizeof(struct reply));
}
if (req->handle) {
req->handle->pending_cb = 1;
d->handle = req->handle;
}
event_deferred_cb_init_(
&d->deferred,
event_get_priority(&req->timeout_event),
reply_run_callback,
req->user_pointer);
event_deferred_cb_schedule_(
req->base->event_base,
&d->deferred);
}
/* this processes a parsed reply packet */
static void
reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
int error;
char addrbuf[128];
static const int error_codes[] = {
DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
};
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (flags & 0x020f || !reply || !reply->have_answer) {
/* there was an error */
if (flags & 0x0200) {
error = DNS_ERR_TRUNCATED;
} else if (flags & 0x000f) {
u16 error_code = (flags & 0x000f) - 1;
if (error_code > 4) {
error = DNS_ERR_UNKNOWN;
} else {
error = error_codes[error_code];
}
} else if (reply && !reply->have_answer) {
error = DNS_ERR_NODATA;
} else {
error = DNS_ERR_UNKNOWN;
}
switch (error) {
case DNS_ERR_NOTIMPL:
case DNS_ERR_REFUSED:
/* we regard these errors as marking a bad nameserver */
if (req->reissue_count < req->base->global_max_reissues) {
char msg[64];
evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
error, evdns_err_to_string(error));
nameserver_failed(req->ns, msg);
if (!request_reissue(req)) return;
}
break;
case DNS_ERR_SERVERFAILED:
/* rcode 2 (servfailed) sometimes means "we
* are broken" and sometimes (with some binds)
* means "that request was very confusing."
* Treat this as a timeout, not a failure.
*/
log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
"at %s; will allow the request to time out.",
evutil_format_sockaddr_port_(
(struct sockaddr *)&req->ns->address,
addrbuf, sizeof(addrbuf)));
/* Call the timeout function */
evdns_request_timeout_callback(0, 0, req);
return;
default:
/* we got a good reply from the nameserver: it is up. */
if (req->handle == req->ns->probe_request) {
/* Avoid double-free */
req->ns->probe_request = NULL;
}
nameserver_up(req->ns);
}
if (req->handle->search_state &&
req->request_type != TYPE_PTR) {
/* if we have a list of domains to search in,
* try the next one */
if (!search_try_next(req->handle)) {
/* a new request was issued so this
* request is finished and */
/* the user callback will be made when
* that request (or a */
/* child of it) finishes. */
return;
}
}
/* all else failed. Pass the failure up */
reply_schedule_callback(req, ttl, error, NULL);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
} else {
/* all ok, tell the user */
reply_schedule_callback(req, ttl, 0, reply);
if (req->handle == req->ns->probe_request)
req->ns->probe_request = NULL; /* Avoid double-free */
nameserver_up(req->ns);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
}
}
static int
name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
int name_end = -1;
int j = *idx;
int ptr_count = 0;
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
char *cp = name_out;
const char *const end = name_out + name_out_len;
/* Normally, names are a series of length prefixed strings terminated */
/* with a length of 0 (the lengths are u8's < 63). */
/* However, the length can start with a pair of 1 bits and that */
/* means that the next 14 bits are a pointer within the current */
/* packet. */
for (;;) {
u8 label_len;
GET8(label_len);
if (!label_len) break;
if (label_len & 0xc0) {
u8 ptr_low;
GET8(ptr_low);
if (name_end < 0) name_end = j;
j = (((int)label_len & 0x3f) << 8) + ptr_low;
/* Make sure that the target offset is in-bounds. */
if (j < 0 || j >= length) return -1;
/* If we've jumped more times than there are characters in the
* message, we must have a loop. */
if (++ptr_count > length) return -1;
continue;
}
if (label_len > 63) return -1;
if (cp != name_out) {
if (cp + 1 >= end) return -1;
*cp++ = '.';
}
if (cp + label_len >= end) return -1;
if (j + label_len > length) return -1;
memcpy(cp, packet + j, label_len);
cp += label_len;
j += label_len;
}
if (cp >= end) return -1;
*cp = '\0';
if (name_end < 0)
*idx = j;
else
*idx = name_end;
return 0;
err:
return -1;
}
/* parses a raw request from a nameserver */
static int
reply_parse(struct evdns_base *base, u8 *packet, int length) {
int j = 0, k = 0; /* index into packet */
u16 t_; /* used by the macros */
u32 t32_; /* used by the macros */
char tmp_name[256], cmp_name[256]; /* used by the macros */
int name_matches = 0;
u16 trans_id, questions, answers, authority, additional, datalength;
u16 flags = 0;
u32 ttl, ttl_r = 0xffffffff;
struct reply reply;
struct request *req = NULL;
unsigned int i;
ASSERT_LOCKED(base);
GET16(trans_id);
GET16(flags);
GET16(questions);
GET16(answers);
GET16(authority);
GET16(additional);
(void) authority; /* suppress "unused variable" warnings. */
(void) additional; /* suppress "unused variable" warnings. */
req = request_find_from_trans_id(base, trans_id);
if (!req) return -1;
EVUTIL_ASSERT(req->base == base);
memset(&reply, 0, sizeof(reply));
/* If it's not an answer, it doesn't correspond to any request. */
if (!(flags & 0x8000)) return -1; /* must be an answer */
if ((flags & 0x020f) && (flags & 0x020f) != DNS_ERR_NOTEXIST) {
/* there was an error and it's not NXDOMAIN */
goto err;
}
/* if (!answers) return; */ /* must have an answer of some form */
/* This macro skips a name in the DNS reply. */
#define SKIP_NAME \
do { tmp_name[0] = '\0'; \
if (name_parse(packet, length, &j, tmp_name, \
sizeof(tmp_name))<0) \
goto err; \
} while (0)
reply.type = req->request_type;
/* skip over each question in the reply */
for (i = 0; i < questions; ++i) {
/* the question looks like
* <label:name><u16:type><u16:class>
*/
tmp_name[0] = '\0';
cmp_name[0] = '\0';
k = j;
if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name)) < 0)
goto err;
if (name_parse(req->request, req->request_len, &k,
cmp_name, sizeof(cmp_name))<0)
goto err;
if (!base->global_randomize_case) {
if (strcmp(tmp_name, cmp_name) == 0)
name_matches = 1;
} else {
if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0)
name_matches = 1;
}
j += 4;
if (j > length)
goto err;
}
if (!name_matches)
goto err;
/* now we have the answer section which looks like
* <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
*/
for (i = 0; i < answers; ++i) {
u16 type, class;
SKIP_NAME;
GET16(type);
GET16(class);
GET32(ttl);
GET16(datalength);
if (type == TYPE_A && class == CLASS_INET) {
int addrcount, addrtocopy;
if (req->request_type != TYPE_A) {
j += datalength; continue;
}
if ((datalength & 3) != 0) /* not an even number of As. */
goto err;
addrcount = datalength >> 2;
addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
ttl_r = MIN(ttl_r, ttl);
/* we only bother with the first four addresses. */
if (j + 4*addrtocopy > length) goto err;
memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
packet + j, 4*addrtocopy);
j += 4*addrtocopy;
reply.data.a.addrcount += addrtocopy;
reply.have_answer = 1;
if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
} else if (type == TYPE_PTR && class == CLASS_INET) {
if (req->request_type != TYPE_PTR) {
j += datalength; continue;
}
if (name_parse(packet, length, &j, reply.data.ptr.name,
sizeof(reply.data.ptr.name))<0)
goto err;
ttl_r = MIN(ttl_r, ttl);
reply.have_answer = 1;
break;
} else if (type == TYPE_CNAME) {
char cname[HOST_NAME_MAX];
if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
j += datalength; continue;
}
if (name_parse(packet, length, &j, cname,
sizeof(cname))<0)
goto err;
*req->put_cname_in_ptr = mm_strdup(cname);
} else if (type == TYPE_AAAA && class == CLASS_INET) {
int addrcount, addrtocopy;
if (req->request_type != TYPE_AAAA) {
j += datalength; continue;
}
if ((datalength & 15) != 0) /* not an even number of AAAAs. */
goto err;
addrcount = datalength >> 4; /* each address is 16 bytes long */
addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
ttl_r = MIN(ttl_r, ttl);
/* we only bother with the first four addresses. */
if (j + 16*addrtocopy > length) goto err;
memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
packet + j, 16*addrtocopy);
reply.data.aaaa.addrcount += addrtocopy;
j += 16*addrtocopy;
reply.have_answer = 1;
if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
} else {
/* skip over any other type of resource */
j += datalength;
}
}
if (!reply.have_answer) {
for (i = 0; i < authority; ++i) {
u16 type, class;
SKIP_NAME;
GET16(type);
GET16(class);
GET32(ttl);
GET16(datalength);
if (type == TYPE_SOA && class == CLASS_INET) {
u32 serial, refresh, retry, expire, minimum;
SKIP_NAME;
SKIP_NAME;
GET32(serial);
GET32(refresh);
GET32(retry);
GET32(expire);
GET32(minimum);
(void)expire;
(void)retry;
(void)refresh;
(void)serial;
ttl_r = MIN(ttl_r, ttl);
ttl_r = MIN(ttl_r, minimum);
} else {
/* skip over any other type of resource */
j += datalength;
}
}
}
if (ttl_r == 0xffffffff)
ttl_r = 0;
reply_handle(req, flags, ttl_r, &reply);
return 0;
err:
if (req)
reply_handle(req, flags, 0, NULL);
return -1;
}
/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
/* callback. */
static int
request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
{
int j = 0; /* index into packet */
u16 t_; /* used by the macros */
char tmp_name[256]; /* used by the macros */
int i;
u16 trans_id, flags, questions, answers, authority, additional;
struct server_request *server_req = NULL;
ASSERT_LOCKED(port);
/* Get the header fields */
GET16(trans_id);
GET16(flags);
GET16(questions);
GET16(answers);
GET16(authority);
GET16(additional);
(void)answers;
(void)additional;
(void)authority;
if (flags & 0x8000) return -1; /* Must not be an answer. */
flags &= 0x0110; /* Only RD and CD get preserved. */
server_req = mm_malloc(sizeof(struct server_request));
if (server_req == NULL) return -1;
memset(server_req, 0, sizeof(struct server_request));
server_req->trans_id = trans_id;
memcpy(&server_req->addr, addr, addrlen);
server_req->addrlen = addrlen;
server_req->base.flags = flags;
server_req->base.nquestions = 0;
server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
if (server_req->base.questions == NULL)
goto err;
for (i = 0; i < questions; ++i) {
u16 type, class;
struct evdns_server_question *q;
int namelen;
if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
goto err;
GET16(type);
GET16(class);
namelen = (int)strlen(tmp_name);
q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
if (!q)
goto err;
q->type = type;
q->dns_question_class = class;
memcpy(q->name, tmp_name, namelen+1);
server_req->base.questions[server_req->base.nquestions++] = q;
}
/* Ignore answers, authority, and additional. */
server_req->port = port;
port->refcnt++;
/* Only standard queries are supported. */
if (flags & 0x7800) {
evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
return -1;
}
port->user_callback(&(server_req->base), port->user_data);
return 0;
err:
if (server_req) {
if (server_req->base.questions) {
for (i = 0; i < server_req->base.nquestions; ++i)
mm_free(server_req->base.questions[i]);
mm_free(server_req->base.questions);
}
mm_free(server_req);
}
return -1;
#undef SKIP_NAME
#undef GET32
#undef GET16
#undef GET8
}
void
evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
{
}
void
evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
{
}
/* Try to choose a strong transaction id which isn't already in flight */
static u16
transaction_id_pick(struct evdns_base *base) {
ASSERT_LOCKED(base);
for (;;) {
u16 trans_id;
evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
if (trans_id == 0xffff) continue;
/* now check to see if that id is already inflight */
if (request_find_from_trans_id(base, trans_id) == NULL)
return trans_id;
}
}
/* choose a namesever to use. This function will try to ignore */
/* nameservers which we think are down and load balance across the rest */
/* by updating the server_head global each time. */
static struct nameserver *
nameserver_pick(struct evdns_base *base) {
struct nameserver *started_at = base->server_head, *picked;
ASSERT_LOCKED(base);
if (!base->server_head) return NULL;
/* if we don't have any good nameservers then there's no */
/* point in trying to find one. */
if (!base->global_good_nameservers) {
base->server_head = base->server_head->next;
return base->server_head;
}
/* remember that nameservers are in a circular list */
for (;;) {
if (base->server_head->state) {
/* we think this server is currently good */
picked = base->server_head;
base->server_head = base->server_head->next;
return picked;
}
base->server_head = base->server_head->next;
if (base->server_head == started_at) {
/* all the nameservers seem to be down */
/* so we just return this one and hope for the */
/* best */
EVUTIL_ASSERT(base->global_good_nameservers == 0);
picked = base->server_head;
base->server_head = base->server_head->next;
return picked;
}
}
}
/* this is called when a namesever socket is ready for reading */
static void
nameserver_read(struct nameserver *ns) {
struct sockaddr_storage ss;
ev_socklen_t addrlen = sizeof(ss);
u8 packet[1500];
char addrbuf[128];
ASSERT_LOCKED(ns->base);
for (;;) {
const int r = recvfrom(ns->socket, (void*)packet,
sizeof(packet), 0,
(struct sockaddr*)&ss, &addrlen);
if (r < 0) {
int err = evutil_socket_geterror(ns->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return;
nameserver_failed(ns,
evutil_socket_error_to_string(err));
return;
}
if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
(struct sockaddr*)&ns->address, 0)) {
log(EVDNS_LOG_WARN, "Address mismatch on received "
"DNS packet. Apparent source was %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ss,
addrbuf, sizeof(addrbuf)));
return;
}
ns->timedout = 0;
reply_parse(ns->base, packet, r);
}
}
/* Read a packet from a DNS client on a server port s, parse it, and */
/* act accordingly. */
static void
server_port_read(struct evdns_server_port *s) {
u8 packet[1500];
struct sockaddr_storage addr;
ev_socklen_t addrlen;
int r;
ASSERT_LOCKED(s);
for (;;) {
addrlen = sizeof(struct sockaddr_storage);
r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
(struct sockaddr*) &addr, &addrlen);
if (r < 0) {
int err = evutil_socket_geterror(s->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return;
log(EVDNS_LOG_WARN,
"Error %s (%d) while reading request.",
evutil_socket_error_to_string(err), err);
return;
}
request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
}
}
/* Try to write all pending replies on a given DNS server port. */
static void
server_port_flush(struct evdns_server_port *port)
{
struct server_request *req = port->pending_replies;
ASSERT_LOCKED(port);
while (req) {
int r = sendto(port->socket, req->response, (int)req->response_len, 0,
(struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
if (r < 0) {
int err = evutil_socket_geterror(port->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return;
log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
}
if (server_request_free(req)) {
/* we released the last reference to req->port. */
return;
} else {
EVUTIL_ASSERT(req != port->pending_replies);
req = port->pending_replies;
}
}
/* We have no more pending requests; stop listening for 'writeable' events. */
(void) event_del(&port->event);
event_assign(&port->event, port->event_base,
port->socket, EV_READ | EV_PERSIST,
server_port_ready_callback, port);
if (event_add(&port->event, NULL) < 0) {
log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
/* ???? Do more? */
}
}
/* set if we are waiting for the ability to write to this server. */
/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
/* we stop these events. */
static void
nameserver_write_waiting(struct nameserver *ns, char waiting) {
ASSERT_LOCKED(ns->base);
if (ns->write_waiting == waiting) return;
ns->write_waiting = waiting;
(void) event_del(&ns->event);
event_assign(&ns->event, ns->base->event_base,
ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
nameserver_ready_callback, ns);
if (event_add(&ns->event, NULL) < 0) {
char addrbuf[128];
log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
/* ???? Do more? */
}
}
/* a callback function. Called by libevent when the kernel says that */
/* a nameserver socket is ready for writing or reading */
static void
nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
struct nameserver *ns = (struct nameserver *) arg;
(void)fd;
EVDNS_LOCK(ns->base);
if (events & EV_WRITE) {
ns->choked = 0;
if (!evdns_transmit(ns->base)) {
nameserver_write_waiting(ns, 0);
}
}
if (events & EV_READ) {
nameserver_read(ns);
}
EVDNS_UNLOCK(ns->base);
}
/* a callback function. Called by libevent when the kernel says that */
/* a server socket is ready for writing or reading. */
static void
server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
struct evdns_server_port *port = (struct evdns_server_port *) arg;
(void) fd;
EVDNS_LOCK(port);
if (events & EV_WRITE) {
port->choked = 0;
server_port_flush(port);
}
if (events & EV_READ) {
server_port_read(port);
}
EVDNS_UNLOCK(port);
}
/* This is an inefficient representation; only use it via the dnslabel_table_*
* functions, so that is can be safely replaced with something smarter later. */
#define MAX_LABELS 128
/* Structures used to implement name compression */
struct dnslabel_entry { char *v; off_t pos; };
struct dnslabel_table {
int n_labels; /* number of current entries */
/* map from name to position in message */
struct dnslabel_entry labels[MAX_LABELS];
};
/* Initialize dnslabel_table. */
static void
dnslabel_table_init(struct dnslabel_table *table)
{
table->n_labels = 0;
}
/* Free all storage held by table, but not the table itself. */
static void
dnslabel_clear(struct dnslabel_table *table)
{
int i;
for (i = 0; i < table->n_labels; ++i)
mm_free(table->labels[i].v);
table->n_labels = 0;
}
/* return the position of the label in the current message, or -1 if the label */
/* hasn't been used yet. */
static int
dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
{
int i;
for (i = 0; i < table->n_labels; ++i) {
if (!strcmp(label, table->labels[i].v))
return table->labels[i].pos;
}
return -1;
}
/* remember that we've used the label at position pos */
static int
dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
{
char *v;
int p;
if (table->n_labels == MAX_LABELS)
return (-1);
v = mm_strdup(label);
if (v == NULL)
return (-1);
p = table->n_labels++;
table->labels[p].v = v;
table->labels[p].pos = pos;
return (0);
}
/* Converts a string to a length-prefixed set of DNS labels, starting */
/* at buf[j]. name and buf must not overlap. name_len should be the length */
/* of name. table is optional, and is used for compression. */
/* */
/* Input: abc.def */
/* Output: <3>abc<3>def<0> */
/* */
/* Returns the first index after the encoded name, or negative on error. */
/* -1 label was > 63 bytes */
/* -2 name too long to fit in buffer. */
/* */
static off_t
dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
const char *name, const size_t name_len,
struct dnslabel_table *table) {
const char *end = name + name_len;
int ref = 0;
u16 t_;
#define APPEND16(x) do { \
if (j + 2 > (off_t)buf_len) \
goto overflow; \
t_ = htons(x); \
memcpy(buf + j, &t_, 2); \
j += 2; \
} while (0)
#define APPEND32(x) do { \
if (j + 4 > (off_t)buf_len) \
goto overflow; \
t32_ = htonl(x); \
memcpy(buf + j, &t32_, 4); \
j += 4; \
} while (0)
if (name_len > 255) return -2;
for (;;) {
const char *const start = name;
if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
APPEND16(ref | 0xc000);
return j;
}
name = strchr(name, '.');
if (!name) {
const size_t label_len = end - start;
if (label_len > 63) return -1;
if ((size_t)(j+label_len+1) > buf_len) return -2;
if (table) dnslabel_table_add(table, start, j);
buf[j++] = (ev_uint8_t)label_len;
memcpy(buf + j, start, label_len);
j += (int) label_len;
break;
} else {
/* append length of the label. */
const size_t label_len = name - start;
if (label_len > 63) return -1;
if ((size_t)(j+label_len+1) > buf_len) return -2;
if (table) dnslabel_table_add(table, start, j);
buf[j++] = (ev_uint8_t)label_len;
memcpy(buf + j, start, label_len);
j += (int) label_len;
/* hop over the '.' */
name++;
}
}
/* the labels must be terminated by a 0. */
/* It's possible that the name ended in a . */
/* in which case the zero is already there */
if (!j || buf[j-1]) buf[j++] = 0;
return j;
overflow:
return (-2);
}
/* Finds the length of a dns request for a DNS name of the given */
/* length. The actual request may be smaller than the value returned */
/* here */
static size_t
evdns_request_len(const size_t name_len) {
return 96 + /* length of the DNS standard header */
name_len + 2 +
4; /* space for the resource type */
}
/* build a dns request packet into buf. buf should be at least as long */
/* as evdns_request_len told you it should be. */
/* */
/* Returns the amount of space used. Negative on error. */
static int
evdns_request_data_build(const char *const name, const size_t name_len,
const u16 trans_id, const u16 type, const u16 class,
u8 *const buf, size_t buf_len) {
off_t j = 0; /* current offset into buf */
u16 t_; /* used by the macros */
APPEND16(trans_id);
APPEND16(0x0100); /* standard query, recusion needed */
APPEND16(1); /* one question */
APPEND16(0); /* no answers */
APPEND16(0); /* no authority */
APPEND16(0); /* no additional */
j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
if (j < 0) {
return (int)j;
}
APPEND16(type);
APPEND16(class);
return (int)j;
overflow:
return (-1);
}
/* exported function */
struct evdns_server_port *
evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
{
struct evdns_server_port *port;
if (flags)
return NULL; /* flags not yet implemented */
if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
return NULL;
memset(port, 0, sizeof(struct evdns_server_port));
port->socket = socket;
port->refcnt = 1;
port->choked = 0;
port->closing = 0;
port->user_callback = cb;
port->user_data = user_data;
port->pending_replies = NULL;
port->event_base = base;
event_assign(&port->event, port->event_base,
port->socket, EV_READ | EV_PERSIST,
server_port_ready_callback, port);
if (event_add(&port->event, NULL) < 0) {
mm_free(port);
return NULL;
}
EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
return port;
}
struct evdns_server_port *
evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
{
return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
}
/* exported function */
void
evdns_close_server_port(struct evdns_server_port *port)
{
EVDNS_LOCK(port);
if (--port->refcnt == 0) {
EVDNS_UNLOCK(port);
server_port_free(port);
} else {
port->closing = 1;
}
}
/* exported function */
int
evdns_server_request_add_reply(struct evdns_server_request *req_, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
struct server_reply_item **itemp, *item;
int *countp;
int result = -1;
EVDNS_LOCK(req->port);
if (req->response) /* have we already answered? */
goto done;
switch (section) {
case EVDNS_ANSWER_SECTION:
itemp = &req->answer;
countp = &req->n_answer;
break;
case EVDNS_AUTHORITY_SECTION:
itemp = &req->authority;
countp = &req->n_authority;
break;
case EVDNS_ADDITIONAL_SECTION:
itemp = &req->additional;
countp = &req->n_additional;
break;
default:
goto done;
}
while (*itemp) {
itemp = &((*itemp)->next);
}
item = mm_malloc(sizeof(struct server_reply_item));
if (!item)
goto done;
item->next = NULL;
if (!(item->name = mm_strdup(name))) {
mm_free(item);
goto done;
}
item->type = type;
item->dns_question_class = class;
item->ttl = ttl;
item->is_name = is_name != 0;
item->datalen = 0;
item->data = NULL;
if (data) {
if (item->is_name) {
if (!(item->data = mm_strdup(data))) {
mm_free(item->name);
mm_free(item);
goto done;
}
item->datalen = (u16)-1;
} else {
if (!(item->data = mm_malloc(datalen))) {
mm_free(item->name);
mm_free(item);
goto done;
}
item->datalen = datalen;
memcpy(item->data, data, datalen);
}
}
*itemp = item;
++(*countp);
result = 0;
done:
EVDNS_UNLOCK(req->port);
return result;
}
/* exported function */
int
evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
{
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
ttl, n*4, 0, addrs);
}
/* exported function */
int
evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
{
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
ttl, n*16, 0, addrs);
}
/* exported function */
int
evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
{
u32 a;
char buf[32];
if (in && inaddr_name)
return -1;
else if (!in && !inaddr_name)
return -1;
if (in) {
a = ntohl(in->s_addr);
evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
(int)(u8)((a )&0xff),
(int)(u8)((a>>8 )&0xff),
(int)(u8)((a>>16)&0xff),
(int)(u8)((a>>24)&0xff));
inaddr_name = buf;
}
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
ttl, -1, 1, hostname);
}
/* exported function */
int
evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
{
return evdns_server_request_add_reply(
req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
ttl, -1, 1, cname);
}
/* exported function */
void
evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
{
struct server_request *req = TO_SERVER_REQUEST(exreq);
req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
req->base.flags |= flags;
}
static int
evdns_server_request_format_response(struct server_request *req, int err)
{
unsigned char buf[1500];
size_t buf_len = sizeof(buf);
off_t j = 0, r;
u16 t_;
u32 t32_;
int i;
u16 flags;
struct dnslabel_table table;
if (err < 0 || err > 15) return -1;
/* Set response bit and error code; copy OPCODE and RD fields from
* question; copy RA and AA if set by caller. */
flags = req->base.flags;
flags |= (0x8000 | err);
dnslabel_table_init(&table);
APPEND16(req->trans_id);
APPEND16(flags);
APPEND16(req->base.nquestions);
APPEND16(req->n_answer);
APPEND16(req->n_authority);
APPEND16(req->n_additional);
/* Add questions. */
for (i=0; i < req->base.nquestions; ++i) {
const char *s = req->base.questions[i]->name;
j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
if (j < 0) {
dnslabel_clear(&table);
return (int) j;
}
APPEND16(req->base.questions[i]->type);
APPEND16(req->base.questions[i]->dns_question_class);
}
/* Add answer, authority, and additional sections. */
for (i=0; i<3; ++i) {
struct server_reply_item *item;
if (i==0)
item = req->answer;
else if (i==1)
item = req->authority;
else
item = req->additional;
while (item) {
r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
if (r < 0)
goto overflow;
j = r;
APPEND16(item->type);
APPEND16(item->dns_question_class);
APPEND32(item->ttl);
if (item->is_name) {
off_t len_idx = j, name_start;
j += 2;
name_start = j;
r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
if (r < 0)
goto overflow;
j = r;
t_ = htons( (short) (j-name_start) );
memcpy(buf+len_idx, &t_, 2);
} else {
APPEND16(item->datalen);
if (j+item->datalen > (off_t)buf_len)
goto overflow;
memcpy(buf+j, item->data, item->datalen);
j += item->datalen;
}
item = item->next;
}
}
if (j > 512) {
overflow:
j = 512;
buf[2] |= 0x02; /* set the truncated bit. */
}
req->response_len = j;
if (!(req->response = mm_malloc(req->response_len))) {
server_request_free_answers(req);
dnslabel_clear(&table);
return (-1);
}
memcpy(req->response, buf, req->response_len);
server_request_free_answers(req);
dnslabel_clear(&table);
return (0);
}
/* exported function */
int
evdns_server_request_respond(struct evdns_server_request *req_, int err)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
struct evdns_server_port *port = req->port;
int r = -1;
EVDNS_LOCK(port);
if (!req->response) {
if ((r = evdns_server_request_format_response(req, err))<0)
goto done;
}
r = sendto(port->socket, req->response, (int)req->response_len, 0,
(struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
if (r<0) {
int sock_err = evutil_socket_geterror(port->socket);
if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
goto done;
if (port->pending_replies) {
req->prev_pending = port->pending_replies->prev_pending;
req->next_pending = port->pending_replies;
req->prev_pending->next_pending =
req->next_pending->prev_pending = req;
} else {
req->prev_pending = req->next_pending = req;
port->pending_replies = req;
port->choked = 1;
(void) event_del(&port->event);
event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
if (event_add(&port->event, NULL) < 0) {
log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
}
}
r = 1;
goto done;
}
if (server_request_free(req)) {
r = 0;
goto done;
}
if (port->pending_replies)
server_port_flush(port);
r = 0;
done:
EVDNS_UNLOCK(port);
return r;
}
/* Free all storage held by RRs in req. */
static void
server_request_free_answers(struct server_request *req)
{
struct server_reply_item *victim, *next, **list;
int i;
for (i = 0; i < 3; ++i) {
if (i==0)
list = &req->answer;
else if (i==1)
list = &req->authority;
else
list = &req->additional;
victim = *list;
while (victim) {
next = victim->next;
mm_free(victim->name);
if (victim->data)
mm_free(victim->data);
mm_free(victim);
victim = next;
}
*list = NULL;
}
}
/* Free all storage held by req, and remove links to it. */
/* return true iff we just wound up freeing the server_port. */
static int
server_request_free(struct server_request *req)
{
int i, rc=1, lock=0;
if (req->base.questions) {
for (i = 0; i < req->base.nquestions; ++i)
mm_free(req->base.questions[i]);
mm_free(req->base.questions);
}
if (req->port) {
EVDNS_LOCK(req->port);
lock=1;
if (req->port->pending_replies == req) {
if (req->next_pending && req->next_pending != req)
req->port->pending_replies = req->next_pending;
else
req->port->pending_replies = NULL;
}
rc = --req->port->refcnt;
}
if (req->response) {
mm_free(req->response);
}
server_request_free_answers(req);
if (req->next_pending && req->next_pending != req) {
req->next_pending->prev_pending = req->prev_pending;
req->prev_pending->next_pending = req->next_pending;
}
if (rc == 0) {
EVDNS_UNLOCK(req->port); /* ????? nickm */
server_port_free(req->port);
mm_free(req);
return (1);
}
if (lock)
EVDNS_UNLOCK(req->port);
mm_free(req);
return (0);
}
/* Free all storage held by an evdns_server_port. Only called when */
static void
server_port_free(struct evdns_server_port *port)
{
EVUTIL_ASSERT(port);
EVUTIL_ASSERT(!port->refcnt);
EVUTIL_ASSERT(!port->pending_replies);
if (port->socket > 0) {
evutil_closesocket(port->socket);
port->socket = -1;
}
(void) event_del(&port->event);
event_debug_unassign(&port->event);
EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
mm_free(port);
}
/* exported function */
int
evdns_server_request_drop(struct evdns_server_request *req_)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
server_request_free(req);
return 0;
}
/* exported function */
int
evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
{
struct server_request *req = TO_SERVER_REQUEST(req_);
if (addr_len < (int)req->addrlen)
return -1;
memcpy(sa, &(req->addr), req->addrlen);
return req->addrlen;
}
#undef APPEND16
#undef APPEND32
/* this is a libevent callback function which is called when a request */
/* has timed out. */
static void
evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
struct request *const req = (struct request *) arg;
struct evdns_base *base = req->base;
(void) fd;
(void) events;
log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
EVDNS_LOCK(base);
if (req->tx_count >= req->base->global_max_retransmits) {
struct nameserver *ns = req->ns;
/* this request has failed */
log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
arg, req->tx_count);
reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
nameserver_failed(ns, "request timed out.");
} else {
/* retransmit it */
log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
arg, req->tx_count);
(void) evtimer_del(&req->timeout_event);
request_swap_ns(req, nameserver_pick(base));
evdns_request_transmit(req);
req->ns->timedout++;
if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
req->ns->timedout = 0;
nameserver_failed(req->ns, "request timed out.");
}
}
EVDNS_UNLOCK(base);
}
/* try to send a request to a given server. */
/* */
/* return: */
/* 0 ok */
/* 1 temporary failure */
/* 2 other failure */
static int
evdns_request_transmit_to(struct request *req, struct nameserver *server) {
int r;
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (server->requests_inflight == 1 &&
req->base->disable_when_inactive &&
event_add(&server->event, NULL) < 0) {
return 1;
}
r = sendto(server->socket, (void*)req->request, req->request_len, 0,
(struct sockaddr *)&server->address, server->addrlen);
if (r < 0) {
int err = evutil_socket_geterror(server->socket);
if (EVUTIL_ERR_RW_RETRIABLE(err))
return 1;
nameserver_failed(req->ns, evutil_socket_error_to_string(err));
return 2;
} else if (r != (int)req->request_len) {
return 1; /* short write */
} else {
return 0;
}
}
/* try to send a request, updating the fields of the request */
/* as needed */
/* */
/* return: */
/* 0 ok */
/* 1 failed */
static int
evdns_request_transmit(struct request *req) {
int retcode = 0, r;
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
/* if we fail to send this packet then this flag marks it */
/* for evdns_transmit */
req->transmit_me = 1;
EVUTIL_ASSERT(req->trans_id != 0xffff);
if (!req->ns)
{
/* unable to transmit request if no nameservers */
return 1;
}
if (req->ns->choked) {
/* don't bother trying to write to a socket */
/* which we have had EAGAIN from */
return 1;
}
r = evdns_request_transmit_to(req, req->ns);
switch (r) {
case 1:
/* temp failure */
req->ns->choked = 1;
nameserver_write_waiting(req->ns, 1);
return 1;
case 2:
/* failed to transmit the request entirely. */
retcode = 1;
/* fall through: we'll set a timeout, which will time out,
* and make us retransmit the request anyway. */
default:
/* all ok */
log(EVDNS_LOG_DEBUG,
"Setting timeout for request %p, sent to nameserver %p", req, req->ns);
if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
log(EVDNS_LOG_WARN,
"Error from libevent when adding timer for request %p",
req);
/* ???? Do more? */
}
req->tx_count++;
req->transmit_me = 0;
return retcode;
}
}
static void
nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
struct nameserver *const ns = (struct nameserver *) arg;
(void) type;
(void) count;
(void) ttl;
(void) addresses;
if (result == DNS_ERR_CANCEL) {
/* We canceled this request because the nameserver came up
* for some other reason. Do not change our opinion about
* the nameserver. */
return;
}
EVDNS_LOCK(ns->base);
ns->probe_request = NULL;
if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
/* this is a good reply */
nameserver_up(ns);
} else {
nameserver_probe_failed(ns);
}
EVDNS_UNLOCK(ns->base);
}
static void
nameserver_send_probe(struct nameserver *const ns) {
struct evdns_request *handle;
struct request *req;
char addrbuf[128];
/* here we need to send a probe to a given nameserver */
/* in the hope that it is up now. */
ASSERT_LOCKED(ns->base);
log(EVDNS_LOG_DEBUG, "Sending probe to %s",
evutil_format_sockaddr_port_(
(struct sockaddr *)&ns->address,
addrbuf, sizeof(addrbuf)));
handle = mm_calloc(1, sizeof(*handle));
if (!handle) return;
req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
if (!req) {
mm_free(handle);
return;
}
ns->probe_request = handle;
/* we force this into the inflight queue no matter what */
request_trans_id_set(req, transaction_id_pick(ns->base));
req->ns = ns;
request_submit(req);
}
/* returns: */
/* 0 didn't try to transmit anything */
/* 1 tried to transmit something */
static int
evdns_transmit(struct evdns_base *base) {
char did_try_to_transmit = 0;
int i;
ASSERT_LOCKED(base);
for (i = 0; i < base->n_req_heads; ++i) {
if (base->req_heads[i]) {
struct request *const started_at = base->req_heads[i], *req = started_at;
/* first transmit all the requests which are currently waiting */
do {
if (req->transmit_me) {
did_try_to_transmit = 1;
evdns_request_transmit(req);
}
req = req->next;
} while (req != started_at);
}
}
return did_try_to_transmit;
}
/* exported function */
int
evdns_base_count_nameservers(struct evdns_base *base)
{
const struct nameserver *server;
int n = 0;
EVDNS_LOCK(base);
server = base->server_head;
if (!server)
goto done;
do {
++n;
server = server->next;
} while (server != base->server_head);
done:
EVDNS_UNLOCK(base);
return n;
}
int
evdns_count_nameservers(void)
{
return evdns_base_count_nameservers(current_base);
}
/* exported function */
int
evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
{
struct nameserver *server, *started_at;
int i;
EVDNS_LOCK(base);
server = base->server_head;
started_at = base->server_head;
if (!server) {
EVDNS_UNLOCK(base);
return 0;
}
while (1) {
struct nameserver *next = server->next;
(void) event_del(&server->event);
if (evtimer_initialized(&server->timeout_event))
(void) evtimer_del(&server->timeout_event);
if (server->probe_request) {
evdns_cancel_request(server->base, server->probe_request);
server->probe_request = NULL;
}
if (server->socket >= 0)
evutil_closesocket(server->socket);
mm_free(server);
if (next == started_at)
break;
server = next;
}
base->server_head = NULL;
base->global_good_nameservers = 0;
for (i = 0; i < base->n_req_heads; ++i) {
struct request *req, *req_started_at;
req = req_started_at = base->req_heads[i];
while (req) {
struct request *next = req->next;
req->tx_count = req->reissue_count = 0;
req->ns = NULL;
/* ???? What to do about searches? */
(void) evtimer_del(&req->timeout_event);
req->trans_id = 0;
req->transmit_me = 0;
base->global_requests_waiting++;
evdns_request_insert(req, &base->req_waiting_head);
/* We want to insert these suspended elements at the front of
* the waiting queue, since they were pending before any of
* the waiting entries were added. This is a circular list,
* so we can just shift the start back by one.*/
base->req_waiting_head = base->req_waiting_head->prev;
if (next == req_started_at)
break;
req = next;
}
base->req_heads[i] = NULL;
}
base->global_requests_inflight = 0;
EVDNS_UNLOCK(base);
return 0;
}
int
evdns_clear_nameservers_and_suspend(void)
{
return evdns_base_clear_nameservers_and_suspend(current_base);
}
/* exported function */
int
evdns_base_resume(struct evdns_base *base)
{
EVDNS_LOCK(base);
evdns_requests_pump_waiting_queue(base);
EVDNS_UNLOCK(base);
return 0;
}
int
evdns_resume(void)
{
return evdns_base_resume(current_base);
}
static int
evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
/* first check to see if we already have this nameserver */
const struct nameserver *server = base->server_head, *const started_at = base->server_head;
struct nameserver *ns;
int err = 0;
char addrbuf[128];
ASSERT_LOCKED(base);
if (server) {
do {
if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
server = server->next;
} while (server != started_at);
}
if (addrlen > (int)sizeof(ns->address)) {
log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
return 2;
}
ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
if (!ns) return -1;
memset(ns, 0, sizeof(struct nameserver));
ns->base = base;
evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
ns->socket = evutil_socket_(address->sa_family,
SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
if (ns->socket < 0) { err = 1; goto out1; }
if (base->global_outgoing_addrlen &&
!evutil_sockaddr_is_loopback_(address)) {
if (bind(ns->socket,
(struct sockaddr*)&base->global_outgoing_address,
base->global_outgoing_addrlen) < 0) {
log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
err = 2;
goto out2;
}
}
memcpy(&ns->address, address, addrlen);
ns->addrlen = addrlen;
ns->state = 1;
event_assign(&ns->event, ns->base->event_base, ns->socket,
EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
if (!base->disable_when_inactive && event_add(&ns->event, NULL) < 0) {
err = 2;
goto out2;
}
log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
/* insert this nameserver into the list of them */
if (!base->server_head) {
ns->next = ns->prev = ns;
base->server_head = ns;
} else {
ns->next = base->server_head->next;
ns->prev = base->server_head;
base->server_head->next = ns;
ns->next->prev = ns;
}
base->global_good_nameservers++;
return 0;
out2:
evutil_closesocket(ns->socket);
out1:
event_debug_unassign(&ns->event);
mm_free(ns);
log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
return err;
}
/* exported function */
int
evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
{
struct sockaddr_in sin;
int res;
memset(&sin, 0, sizeof(sin));
sin.sin_addr.s_addr = address;
sin.sin_port = htons(53);
sin.sin_family = AF_INET;
EVDNS_LOCK(base);
res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
EVDNS_UNLOCK(base);
return res;
}
int
evdns_nameserver_add(unsigned long int address) {
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_nameserver_add(current_base, address);
}
static void
sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
{
if (sa->sa_family == AF_INET) {
((struct sockaddr_in *)sa)->sin_port = htons(port);
} else if (sa->sa_family == AF_INET6) {
((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
}
}
static ev_uint16_t
sockaddr_getport(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return ntohs(((struct sockaddr_in *)sa)->sin_port);
} else if (sa->sa_family == AF_INET6) {
return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
} else {
return 0;
}
}
/* exported function */
int
evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
struct sockaddr_storage ss;
struct sockaddr *sa;
int len = sizeof(ss);
int res;
if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
&len)) {
log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
ip_as_string);
return 4;
}
sa = (struct sockaddr *) &ss;
if (sockaddr_getport(sa) == 0)
sockaddr_setport(sa, 53);
EVDNS_LOCK(base);
res = evdns_nameserver_add_impl_(base, sa, len);
EVDNS_UNLOCK(base);
return res;
}
int
evdns_nameserver_ip_add(const char *ip_as_string) {
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_nameserver_ip_add(current_base, ip_as_string);
}
int
evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
{
int res;
EVUTIL_ASSERT(base);
EVDNS_LOCK(base);
res = evdns_nameserver_add_impl_(base, sa, len);
EVDNS_UNLOCK(base);
return res;
}
int
evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
struct sockaddr *sa, ev_socklen_t len)
{
int result = -1;
int i;
struct nameserver *server;
EVDNS_LOCK(base);
server = base->server_head;
for (i = 0; i < idx && server; ++i, server = server->next) {
if (server->next == base->server_head)
goto done;
}
if (! server)
goto done;
if (server->addrlen > len) {
result = (int) server->addrlen;
goto done;
}
memcpy(sa, &server->address, server->addrlen);
result = (int) server->addrlen;
done:
EVDNS_UNLOCK(base);
return result;
}
/* remove from the queue */
static void
evdns_request_remove(struct request *req, struct request **head)
{
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
#if 0
{
struct request *ptr;
int found = 0;
EVUTIL_ASSERT(*head != NULL);
ptr = *head;
do {
if (ptr == req) {
found = 1;
break;
}
ptr = ptr->next;
} while (ptr != *head);
EVUTIL_ASSERT(found);
EVUTIL_ASSERT(req->next);
}
#endif
if (req->next == req) {
/* only item in the list */
*head = NULL;
} else {
req->next->prev = req->prev;
req->prev->next = req->next;
if (*head == req) *head = req->next;
}
req->next = req->prev = NULL;
}
/* insert into the tail of the queue */
static void
evdns_request_insert(struct request *req, struct request **head) {
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (!*head) {
*head = req;
req->next = req->prev = req;
return;
}
req->prev = (*head)->prev;
req->prev->next = req;
req->next = *head;
(*head)->prev = req;
}
static int
string_num_dots(const char *s) {
int count = 0;
while ((s = strchr(s, '.'))) {
s++;
count++;
}
return count;
}
static struct request *
request_new(struct evdns_base *base, struct evdns_request *handle, int type,
const char *name, int flags, evdns_callback_type callback,
void *user_ptr) {
const char issuing_now =
(base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
const size_t name_len = strlen(name);
const size_t request_max_len = evdns_request_len(name_len);
const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
/* the request data is alloced in a single block with the header */
struct request *const req =
mm_malloc(sizeof(struct request) + request_max_len);
int rlen;
char namebuf[256];
(void) flags;
ASSERT_LOCKED(base);
if (!req) return NULL;
if (name_len >= sizeof(namebuf)) {
mm_free(req);
return NULL;
}
memset(req, 0, sizeof(struct request));
req->base = base;
evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
if (base->global_randomize_case) {
unsigned i;
char randbits[(sizeof(namebuf)+7)/8];
strlcpy(namebuf, name, sizeof(namebuf));
evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
for (i = 0; i < name_len; ++i) {
if (EVUTIL_ISALPHA_(namebuf[i])) {
if ((randbits[i >> 3] & (1<<(i & 7))))
namebuf[i] |= 0x20;
else
namebuf[i] &= ~0x20;
}
}
name = namebuf;
}
/* request data lives just after the header */
req->request = ((u8 *) req) + sizeof(struct request);
/* denotes that the request data shouldn't be free()ed */
req->request_appended = 1;
rlen = evdns_request_data_build(name, name_len, trans_id,
type, CLASS_INET, req->request, request_max_len);
if (rlen < 0)
goto err1;
req->request_len = rlen;
req->trans_id = trans_id;
req->tx_count = 0;
req->request_type = type;
req->user_pointer = user_ptr;
req->user_callback = callback;
req->ns = issuing_now ? nameserver_pick(base) : NULL;
req->next = req->prev = NULL;
req->handle = handle;
if (handle) {
handle->current_req = req;
handle->base = base;
}
return req;
err1:
mm_free(req);
return NULL;
}
static void
request_submit(struct request *const req) {
struct evdns_base *base = req->base;
ASSERT_LOCKED(base);
ASSERT_VALID_REQUEST(req);
if (req->ns) {
/* if it has a nameserver assigned then this is going */
/* straight into the inflight queue */
evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
base->global_requests_inflight++;
req->ns->requests_inflight++;
evdns_request_transmit(req);
} else {
evdns_request_insert(req, &base->req_waiting_head);
base->global_requests_waiting++;
}
}
/* exported function */
void
evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
{
struct request *req;
if (!handle->current_req)
return;
if (!base) {
/* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
base = handle->base;
if (!base)
base = handle->current_req->base;
}
EVDNS_LOCK(base);
if (handle->pending_cb) {
EVDNS_UNLOCK(base);
return;
}
req = handle->current_req;
ASSERT_VALID_REQUEST(req);
reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
if (req->ns) {
/* remove from inflight queue */
request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
} else {
/* remove from global_waiting head */
request_finished(req, &base->req_waiting_head, 1);
}
EVDNS_UNLOCK(base);
}
/* exported function */
struct evdns_request *
evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
evdns_callback_type callback, void *ptr) {
struct evdns_request *handle;
struct request *req;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
EVDNS_LOCK(base);
if (flags & DNS_QUERY_NO_SEARCH) {
req =
request_new(base, handle, TYPE_A, name, flags,
callback, ptr);
if (req)
request_submit(req);
} else {
search_request_new(base, handle, TYPE_A, name, flags,
callback, ptr);
}
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return handle;
}
int evdns_resolve_ipv4(const char *name, int flags,
evdns_callback_type callback, void *ptr)
{
return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
? 0 : -1;
}
/* exported function */
struct evdns_request *
evdns_base_resolve_ipv6(struct evdns_base *base,
const char *name, int flags,
evdns_callback_type callback, void *ptr)
{
struct evdns_request *handle;
struct request *req;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
EVDNS_LOCK(base);
if (flags & DNS_QUERY_NO_SEARCH) {
req = request_new(base, handle, TYPE_AAAA, name, flags,
callback, ptr);
if (req)
request_submit(req);
} else {
search_request_new(base, handle, TYPE_AAAA, name, flags,
callback, ptr);
}
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return handle;
}
int evdns_resolve_ipv6(const char *name, int flags,
evdns_callback_type callback, void *ptr) {
return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
? 0 : -1;
}
struct evdns_request *
evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
char buf[32];
struct evdns_request *handle;
struct request *req;
u32 a;
EVUTIL_ASSERT(in);
a = ntohl(in->s_addr);
evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
(int)(u8)((a )&0xff),
(int)(u8)((a>>8 )&0xff),
(int)(u8)((a>>16)&0xff),
(int)(u8)((a>>24)&0xff));
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
EVDNS_LOCK(base);
req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
if (req)
request_submit(req);
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return (handle);
}
int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
? 0 : -1;
}
struct evdns_request *
evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
/* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
char buf[73];
char *cp;
struct evdns_request *handle;
struct request *req;
int i;
EVUTIL_ASSERT(in);
cp = buf;
for (i=15; i >= 0; --i) {
u8 byte = in->s6_addr[i];
*cp++ = "0123456789abcdef"[byte & 0x0f];
*cp++ = '.';
*cp++ = "0123456789abcdef"[byte >> 4];
*cp++ = '.';
}
EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
handle = mm_calloc(1, sizeof(*handle));
if (handle == NULL)
return NULL;
log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
EVDNS_LOCK(base);
req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
if (req)
request_submit(req);
if (handle->current_req == NULL) {
mm_free(handle);
handle = NULL;
}
EVDNS_UNLOCK(base);
return (handle);
}
int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
? 0 : -1;
}
/* ================================================================= */
/* Search support */
/* */
/* the libc resolver has support for searching a number of domains */
/* to find a name. If nothing else then it takes the single domain */
/* from the gethostname() call. */
/* */
/* It can also be configured via the domain and search options in a */
/* resolv.conf. */
/* */
/* The ndots option controls how many dots it takes for the resolver */
/* to decide that a name is non-local and so try a raw lookup first. */
struct search_domain {
int len;
struct search_domain *next;
/* the text string is appended to this structure */
};
struct search_state {
int refcount;
int ndots;
int num_domains;
struct search_domain *head;
};
static void
search_state_decref(struct search_state *const state) {
if (!state) return;
state->refcount--;
if (!state->refcount) {
struct search_domain *next, *dom;
for (dom = state->head; dom; dom = next) {
next = dom->next;
mm_free(dom);
}
mm_free(state);
}
}
static struct search_state *
search_state_new(void) {
struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
if (!state) return NULL;
memset(state, 0, sizeof(struct search_state));
state->refcount = 1;
state->ndots = 1;
return state;
}
static void
search_postfix_clear(struct evdns_base *base) {
search_state_decref(base->global_search_state);
base->global_search_state = search_state_new();
}
/* exported function */
void
evdns_base_search_clear(struct evdns_base *base)
{
EVDNS_LOCK(base);
search_postfix_clear(base);
EVDNS_UNLOCK(base);
}
void
evdns_search_clear(void) {
evdns_base_search_clear(current_base);
}
static void
search_postfix_add(struct evdns_base *base, const char *domain) {
size_t domain_len;
struct search_domain *sdomain;
while (domain[0] == '.') domain++;
domain_len = strlen(domain);
ASSERT_LOCKED(base);
if (!base->global_search_state) base->global_search_state = search_state_new();
if (!base->global_search_state) return;
base->global_search_state->num_domains++;
sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
if (!sdomain) return;
memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
sdomain->next = base->global_search_state->head;
sdomain->len = (int) domain_len;
base->global_search_state->head = sdomain;
}
/* reverse the order of members in the postfix list. This is needed because, */
/* when parsing resolv.conf we push elements in the wrong order */
static void
search_reverse(struct evdns_base *base) {
struct search_domain *cur, *prev = NULL, *next;
ASSERT_LOCKED(base);
cur = base->global_search_state->head;
while (cur) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
base->global_search_state->head = prev;
}
/* exported function */
void
evdns_base_search_add(struct evdns_base *base, const char *domain) {
EVDNS_LOCK(base);
search_postfix_add(base, domain);
EVDNS_UNLOCK(base);
}
void
evdns_search_add(const char *domain) {
evdns_base_search_add(current_base, domain);
}
/* exported function */
void
evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
EVDNS_LOCK(base);
if (!base->global_search_state) base->global_search_state = search_state_new();
if (base->global_search_state)
base->global_search_state->ndots = ndots;
EVDNS_UNLOCK(base);
}
void
evdns_search_ndots_set(const int ndots) {
evdns_base_search_ndots_set(current_base, ndots);
}
static void
search_set_from_hostname(struct evdns_base *base) {
char hostname[HOST_NAME_MAX + 1], *domainname;
ASSERT_LOCKED(base);
search_postfix_clear(base);
if (gethostname(hostname, sizeof(hostname))) return;
domainname = strchr(hostname, '.');
if (!domainname) return;
search_postfix_add(base, domainname);
}
/* warning: returns malloced string */
static char *
search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
char need_to_append_dot;
struct search_domain *dom;
if (!base_len) return NULL;
need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
for (dom = state->head; dom; dom = dom->next) {
if (!n--) {
/* this is the postfix we want */
/* the actual postfix string is kept at the end of the structure */
const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
const int postfix_len = dom->len;
char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
if (!newname) return NULL;
memcpy(newname, base_name, base_len);
if (need_to_append_dot) newname[base_len] = '.';
memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
newname[base_len + need_to_append_dot + postfix_len] = 0;
return newname;
}
}
/* we ran off the end of the list and still didn't find the requested string */
EVUTIL_ASSERT(0);
return NULL; /* unreachable; stops warnings in some compilers. */
}
static struct request *
search_request_new(struct evdns_base *base, struct evdns_request *handle,
int type, const char *const name, int flags,
evdns_callback_type user_callback, void *user_arg) {
ASSERT_LOCKED(base);
EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
EVUTIL_ASSERT(handle->current_req == NULL);
if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
base->global_search_state &&
base->global_search_state->num_domains) {
/* we have some domains to search */
struct request *req;
if (string_num_dots(name) >= base->global_search_state->ndots) {
req = request_new(base, handle, type, name, flags, user_callback, user_arg);
if (!req) return NULL;
handle->search_index = -1;
} else {
char *const new_name = search_make_new(base->global_search_state, 0, name);
if (!new_name) return NULL;
req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
mm_free(new_name);
if (!req) return NULL;
handle->search_index = 0;
}
EVUTIL_ASSERT(handle->search_origname == NULL);
handle->search_origname = mm_strdup(name);
if (handle->search_origname == NULL) {
/* XXX Should we dealloc req? If yes, how? */
if (req)
mm_free(req);
return NULL;
}
handle->search_state = base->global_search_state;
handle->search_flags = flags;
base->global_search_state->refcount++;
request_submit(req);
return req;
} else {
struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
if (!req) return NULL;
request_submit(req);
return req;
}
}
/* this is called when a request has failed to find a name. We need to check */
/* if it is part of a search and, if so, try the next name in the list */
/* returns: */
/* 0 another request has been submitted */
/* 1 no more requests needed */
static int
search_try_next(struct evdns_request *const handle) {
struct request *req = handle->current_req;
struct evdns_base *base = req->base;
struct request *newreq;
ASSERT_LOCKED(base);
if (handle->search_state) {
/* it is part of a search */
char *new_name;
handle->search_index++;
if (handle->search_index >= handle->search_state->num_domains) {
/* no more postfixes to try, however we may need to try */
/* this name without a postfix */
if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
/* yep, we need to try it raw */
newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
if (newreq) {
search_request_finished(handle);
goto submit_next;
}
}
return 1;
}
new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
if (!new_name) return 1;
log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
mm_free(new_name);
if (!newreq) return 1;
goto submit_next;
}
return 1;
submit_next:
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
handle->current_req = newreq;
newreq->handle = handle;
request_submit(newreq);
return 0;
}
static void
search_request_finished(struct evdns_request *const handle) {
ASSERT_LOCKED(handle->current_req->base);
if (handle->search_state) {
search_state_decref(handle->search_state);
handle->search_state = NULL;
}
if (handle->search_origname) {
mm_free(handle->search_origname);
handle->search_origname = NULL;
}
}
/* ================================================================= */
/* Parsing resolv.conf files */
static void
evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
/* if the file isn't found then we assume a local resolver */
ASSERT_LOCKED(base);
if (flags & DNS_OPTION_SEARCH) search_set_from_hostname(base);
if (flags & DNS_OPTION_NAMESERVERS) evdns_base_nameserver_ip_add(base,"127.0.0.1");
}
#ifndef EVENT__HAVE_STRTOK_R
static char *
strtok_r(char *s, const char *delim, char **state) {
char *cp, *start;
start = cp = s ? s : *state;
if (!cp)
return NULL;
while (*cp && !strchr(delim, *cp))
++cp;
if (!*cp) {
if (cp == start)
return NULL;
*state = NULL;
return start;
} else {
*cp++ = '\0';
*state = cp;
return start;
}
}
#endif
/* helper version of atoi which returns -1 on error */
static int
strtoint(const char *const str)
{
char *endptr;
const int r = strtol(str, &endptr, 10);
if (*endptr) return -1;
return r;
}
/* Parse a number of seconds into a timeval; return -1 on error. */
static int
evdns_strtotimeval(const char *const str, struct timeval *out)
{
double d;
char *endptr;
d = strtod(str, &endptr);
if (*endptr) return -1;
if (d < 0) return -1;
out->tv_sec = (int) d;
out->tv_usec = (int) ((d - (int) d)*1000000);
if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
return -1;
return 0;
}
/* helper version of atoi that returns -1 on error and clips to bounds. */
static int
strtoint_clipped(const char *const str, int min, int max)
{
int r = strtoint(str);
if (r == -1)
return r;
else if (r<min)
return min;
else if (r>max)
return max;
else
return r;
}
static int
evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
{
int old_n_heads = base->n_req_heads, n_heads;
struct request **old_heads = base->req_heads, **new_heads, *req;
int i;
ASSERT_LOCKED(base);
if (maxinflight < 1)
maxinflight = 1;
n_heads = (maxinflight+4) / 5;
EVUTIL_ASSERT(n_heads > 0);
new_heads = mm_calloc(n_heads, sizeof(struct request*));
if (!new_heads)
return (-1);
if (old_heads) {
for (i = 0; i < old_n_heads; ++i) {
while (old_heads[i]) {
req = old_heads[i];
evdns_request_remove(req, &old_heads[i]);
evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
}
}
mm_free(old_heads);
}
base->req_heads = new_heads;
base->n_req_heads = n_heads;
base->global_max_requests_inflight = maxinflight;
return (0);
}
/* exported function */
int
evdns_base_set_option(struct evdns_base *base,
const char *option, const char *val)
{
int res;
EVDNS_LOCK(base);
res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
EVDNS_UNLOCK(base);
return res;
}
static inline int
str_matches_option(const char *s1, const char *optionname)
{
/* Option names are given as "option:" We accept either 'option' in
* s1, or 'option:randomjunk'. The latter form is to implement the
* resolv.conf parser. */
size_t optlen = strlen(optionname);
size_t slen = strlen(s1);
if (slen == optlen || slen == optlen - 1)
return !strncmp(s1, optionname, slen);
else if (slen > optlen)
return !strncmp(s1, optionname, optlen);
else
return 0;
}
static int
evdns_base_set_option_impl(struct evdns_base *base,
const char *option, const char *val, int flags)
{
ASSERT_LOCKED(base);
if (str_matches_option(option, "ndots:")) {
const int ndots = strtoint(val);
if (ndots == -1) return -1;
if (!(flags & DNS_OPTION_SEARCH)) return 0;
log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
if (!base->global_search_state) base->global_search_state = search_state_new();
if (!base->global_search_state) return -1;
base->global_search_state->ndots = ndots;
} else if (str_matches_option(option, "timeout:")) {
struct timeval tv;
if (evdns_strtotimeval(val, &tv) == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
} else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
struct timeval tv;
if (evdns_strtotimeval(val, &tv) == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
val);
memcpy(&base->global_getaddrinfo_allow_skew, &tv,
sizeof(struct timeval));
} else if (str_matches_option(option, "max-timeouts:")) {
const int maxtimeout = strtoint_clipped(val, 1, 255);
if (maxtimeout == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
maxtimeout);
base->global_max_nameserver_timeout = maxtimeout;
} else if (str_matches_option(option, "max-inflight:")) {
const int maxinflight = strtoint_clipped(val, 1, 65000);
if (maxinflight == -1) return -1;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
maxinflight);
evdns_base_set_max_requests_inflight(base, maxinflight);
} else if (str_matches_option(option, "attempts:")) {
int retries = strtoint(val);
if (retries == -1) return -1;
if (retries > 255) retries = 255;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
base->global_max_retransmits = retries;
} else if (str_matches_option(option, "randomize-case:")) {
int randcase = strtoint(val);
if (!(flags & DNS_OPTION_MISC)) return 0;
base->global_randomize_case = randcase;
} else if (str_matches_option(option, "bind-to:")) {
/* XXX This only applies to successive nameservers, not
* to already-configured ones. We might want to fix that. */
int len = sizeof(base->global_outgoing_address);
if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
if (evutil_parse_sockaddr_port(val,
(struct sockaddr*)&base->global_outgoing_address, &len))
return -1;
base->global_outgoing_addrlen = len;
} else if (str_matches_option(option, "initial-probe-timeout:")) {
struct timeval tv;
if (evdns_strtotimeval(val, &tv) == -1) return -1;
if (tv.tv_sec > 3600)
tv.tv_sec = 3600;
if (!(flags & DNS_OPTION_MISC)) return 0;
log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
val);
memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
sizeof(tv));
}
return 0;
}
int
evdns_set_option(const char *option, const char *val, int flags)
{
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_set_option(current_base, option, val);
}
static void
resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
char *strtok_state;
static const char *const delims = " \t";
#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
char *const first_token = strtok_r(start, delims, &strtok_state);
ASSERT_LOCKED(base);
if (!first_token) return;
if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
const char *const nameserver = NEXT_TOKEN;
if (nameserver)
evdns_base_nameserver_ip_add(base, nameserver);
} else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
const char *const domain = NEXT_TOKEN;
if (domain) {
search_postfix_clear(base);
search_postfix_add(base, domain);
}
} else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
const char *domain;
search_postfix_clear(base);
while ((domain = NEXT_TOKEN)) {
search_postfix_add(base, domain);
}
search_reverse(base);
} else if (!strcmp(first_token, "options")) {
const char *option;
while ((option = NEXT_TOKEN)) {
const char *val = strchr(option, ':');
evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
}
}
#undef NEXT_TOKEN
}
/* exported function */
/* returns: */
/* 0 no errors */
/* 1 failed to open file */
/* 2 failed to stat file */
/* 3 file too large */
/* 4 out of memory */
/* 5 short read from file */
int
evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
int res;
EVDNS_LOCK(base);
res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
EVDNS_UNLOCK(base);
return res;
}
static char *
evdns_get_default_hosts_filename(void)
{
#ifdef _WIN32
/* Windows is a little coy about where it puts its configuration
* files. Sure, they're _usually_ in C:\windows\system32, but
* there's no reason in principle they couldn't be in
* W:\hoboken chicken emergency\
*/
char path[MAX_PATH+1];
static const char hostfile[] = "\\drivers\\etc\\hosts";
char *path_out;
size_t len_out;
if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
return NULL;
len_out = strlen(path)+strlen(hostfile)+1;
path_out = mm_malloc(len_out);
evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
return path_out;
#else
return mm_strdup("/etc/hosts");
#endif
}
static int
evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
size_t n;
char *resolv;
char *start;
int err = 0;
log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
if (flags & DNS_OPTION_HOSTSFILE) {
char *fname = evdns_get_default_hosts_filename();
evdns_base_load_hosts(base, fname);
if (fname)
mm_free(fname);
}
if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
if (err == -1) {
/* No file. */
evdns_resolv_set_defaults(base, flags);
return 1;
} else {
return 2;
}
}
start = resolv;
for (;;) {
char *const newline = strchr(start, '\n');
if (!newline) {
resolv_conf_parse_line(base, start, flags);
break;
} else {
*newline = 0;
resolv_conf_parse_line(base, start, flags);
start = newline + 1;
}
}
if (!base->server_head && (flags & DNS_OPTION_NAMESERVERS)) {
/* no nameservers were configured. */
evdns_base_nameserver_ip_add(base, "127.0.0.1");
err = 6;
}
if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
search_set_from_hostname(base);
}
mm_free(resolv);
return err;
}
int
evdns_resolv_conf_parse(int flags, const char *const filename) {
if (!current_base)
current_base = evdns_base_new(NULL, 0);
return evdns_base_resolv_conf_parse(current_base, flags, filename);
}
#ifdef _WIN32
/* Add multiple nameservers from a space-or-comma-separated list. */
static int
evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
const char *addr;
char *buf;
int r;
ASSERT_LOCKED(base);
while (*ips) {
while (isspace(*ips) || *ips == ',' || *ips == '\t')
++ips;
addr = ips;
while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
*ips=='[' || *ips==']')
++ips;
buf = mm_malloc(ips-addr+1);
if (!buf) return 4;
memcpy(buf, addr, ips-addr);
buf[ips-addr] = '\0';
r = evdns_base_nameserver_ip_add(base, buf);
mm_free(buf);
if (r) return r;
}
return 0;
}
typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
/* figure out what our nameservers are. */
static int
load_nameservers_with_getnetworkparams(struct evdns_base *base)
{
/* Based on MSDN examples and inspection of c-ares code. */
FIXED_INFO *fixed;
HMODULE handle = 0;
ULONG size = sizeof(FIXED_INFO);
void *buf = NULL;
int status = 0, r, added_any;
IP_ADDR_STRING *ns;
GetNetworkParams_fn_t fn;
ASSERT_LOCKED(base);
if (!(handle = evutil_load_windows_system_library_(
TEXT("iphlpapi.dll")))) {
log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
status = -1;
goto done;
}
if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
log(EVDNS_LOG_WARN, "Could not get address of function.");
status = -1;
goto done;
}
buf = mm_malloc(size);
if (!buf) { status = 4; goto done; }
fixed = buf;
r = fn(fixed, &size);
if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
status = -1;
goto done;
}
if (r != ERROR_SUCCESS) {
mm_free(buf);
buf = mm_malloc(size);
if (!buf) { status = 4; goto done; }
fixed = buf;
r = fn(fixed, &size);
if (r != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG, "fn() failed.");
status = -1;
goto done;
}
}
EVUTIL_ASSERT(fixed);
added_any = 0;
ns = &(fixed->DnsServerList);
while (ns) {
r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
if (r) {
log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
(ns->IpAddress.String),(int)GetLastError());
status = r;
} else {
++added_any;
log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
}
ns = ns->Next;
}
if (!added_any) {
log(EVDNS_LOG_DEBUG, "No nameservers added.");
if (status == 0)
status = -1;
} else {
status = 0;
}
done:
if (buf)
mm_free(buf);
if (handle)
FreeLibrary(handle);
return status;
}
static int
config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
{
char *buf;
DWORD bufsz = 0, type = 0;
int status = 0;
ASSERT_LOCKED(base);
if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
!= ERROR_MORE_DATA)
return -1;
if (!(buf = mm_malloc(bufsz)))
return -1;
if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
== ERROR_SUCCESS && bufsz > 1) {
status = evdns_nameserver_ip_add_line(base,buf);
}
mm_free(buf);
return status;
}
#define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
#define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
#define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
static int
load_nameservers_from_registry(struct evdns_base *base)
{
int found = 0;
int r;
#define TRY(k, name) \
if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
found = 1; \
} else if (!found) { \
log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
#k,#name); \
}
ASSERT_LOCKED(base);
if (((int)GetVersion()) > 0) { /* NT */
HKEY nt_key = 0, interfaces_key = 0;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
KEY_READ, &nt_key) != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
return -1;
}
r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
&interfaces_key);
if (r != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
return -1;
}
TRY(nt_key, "NameServer");
TRY(nt_key, "DhcpNameServer");
TRY(interfaces_key, "NameServer");
TRY(interfaces_key, "DhcpNameServer");
RegCloseKey(interfaces_key);
RegCloseKey(nt_key);
} else {
HKEY win_key = 0;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
KEY_READ, &win_key) != ERROR_SUCCESS) {
log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
return -1;
}
TRY(win_key, "NameServer");
RegCloseKey(win_key);
}
if (found == 0) {
log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
}
return found ? 0 : -1;
#undef TRY
}
int
evdns_base_config_windows_nameservers(struct evdns_base *base)
{
int r;
char *fname;
if (base == NULL)
base = current_base;
if (base == NULL)
return -1;
EVDNS_LOCK(base);
fname = evdns_get_default_hosts_filename();
log(EVDNS_LOG_DEBUG, "Loading hosts entries from %s", fname);
evdns_base_load_hosts(base, fname);
if (fname)
mm_free(fname);
if (load_nameservers_with_getnetworkparams(base) == 0) {
EVDNS_UNLOCK(base);
return 0;
}
r = load_nameservers_from_registry(base);
EVDNS_UNLOCK(base);
return r;
}
int
evdns_config_windows_nameservers(void)
{
if (!current_base) {
current_base = evdns_base_new(NULL, 1);
return current_base == NULL ? -1 : 0;
} else {
return evdns_base_config_windows_nameservers(current_base);
}
}
#endif
struct evdns_base *
evdns_base_new(struct event_base *event_base, int flags)
{
struct evdns_base *base;
if (evutil_secure_rng_init() < 0) {
log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
"DNS can't run.");
return NULL;
}
/* Give the evutil library a hook into its evdns-enabled
* functionality. We can't just call evdns_getaddrinfo directly or
* else libevent-core will depend on libevent-extras. */
evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel);
base = mm_malloc(sizeof(struct evdns_base));
if (base == NULL)
return (NULL);
memset(base, 0, sizeof(struct evdns_base));
base->req_waiting_head = NULL;
EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
EVDNS_LOCK(base);
/* Set max requests inflight and allocate req_heads. */
base->req_heads = NULL;
evdns_base_set_max_requests_inflight(base, 64);
base->server_head = NULL;
base->event_base = event_base;
base->global_good_nameservers = base->global_requests_inflight =
base->global_requests_waiting = 0;
base->global_timeout.tv_sec = 5;
base->global_timeout.tv_usec = 0;
base->global_max_reissues = 1;
base->global_max_retransmits = 3;
base->global_max_nameserver_timeout = 3;
base->global_search_state = NULL;
base->global_randomize_case = 1;
base->global_getaddrinfo_allow_skew.tv_sec = 3;
base->global_getaddrinfo_allow_skew.tv_usec = 0;
base->global_nameserver_probe_initial_timeout.tv_sec = 10;
base->global_nameserver_probe_initial_timeout.tv_usec = 0;
TAILQ_INIT(&base->hostsdb);
#define EVDNS_BASE_ALL_FLAGS (0x8001)
if (flags & ~EVDNS_BASE_ALL_FLAGS) {
flags = EVDNS_BASE_INITIALIZE_NAMESERVERS;
log(EVDNS_LOG_WARN,
"Unrecognized flag passed to evdns_base_new(). Assuming "
"you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
}
#undef EVDNS_BASE_ALL_FLAGS
if (flags & EVDNS_BASE_INITIALIZE_NAMESERVERS) {
int r;
#ifdef _WIN32
r = evdns_base_config_windows_nameservers(base);
#else
r = evdns_base_resolv_conf_parse(base, DNS_OPTIONS_ALL, "/etc/resolv.conf");
#endif
if (r == -1) {
evdns_base_free_and_unlock(base, 0);
return NULL;
}
}
if (flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE) {
base->disable_when_inactive = 1;
}
EVDNS_UNLOCK(base);
return base;
}
int
evdns_init(void)
{
struct evdns_base *base = evdns_base_new(NULL, 1);
if (base) {
current_base = base;
return 0;
} else {
return -1;
}
}
const char *
evdns_err_to_string(int err)
{
switch (err) {
case DNS_ERR_NONE: return "no error";
case DNS_ERR_FORMAT: return "misformatted query";
case DNS_ERR_SERVERFAILED: return "server failed";
case DNS_ERR_NOTEXIST: return "name does not exist";
case DNS_ERR_NOTIMPL: return "query not implemented";
case DNS_ERR_REFUSED: return "refused";
case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
case DNS_ERR_UNKNOWN: return "unknown";
case DNS_ERR_TIMEOUT: return "request timed out";
case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
case DNS_ERR_CANCEL: return "dns request canceled";
case DNS_ERR_NODATA: return "no records in the reply";
default: return "[Unknown error code]";
}
}
static void
evdns_nameserver_free(struct nameserver *server)
{
if (server->socket >= 0)
evutil_closesocket(server->socket);
(void) event_del(&server->event);
event_debug_unassign(&server->event);
if (server->state == 0)
(void) event_del(&server->timeout_event);
if (server->probe_request) {
evdns_cancel_request(server->base, server->probe_request);
server->probe_request = NULL;
}
event_debug_unassign(&server->timeout_event);
mm_free(server);
}
static void
evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
{
struct nameserver *server, *server_next;
struct search_domain *dom, *dom_next;
int i;
/* Requires that we hold the lock. */
/* TODO(nickm) we might need to refcount here. */
for (i = 0; i < base->n_req_heads; ++i) {
while (base->req_heads[i]) {
if (fail_requests)
reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
}
}
while (base->req_waiting_head) {
if (fail_requests)
reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
}
base->global_requests_inflight = base->global_requests_waiting = 0;
for (server = base->server_head; server; server = server_next) {
server_next = server->next;
/** already done something before */
server->probe_request = NULL;
evdns_nameserver_free(server);
if (server_next == base->server_head)
break;
}
base->server_head = NULL;
base->global_good_nameservers = 0;
if (base->global_search_state) {
for (dom = base->global_search_state->head; dom; dom = dom_next) {
dom_next = dom->next;
mm_free(dom);
}
mm_free(base->global_search_state);
base->global_search_state = NULL;
}
{
struct hosts_entry *victim;
while ((victim = TAILQ_FIRST(&base->hostsdb))) {
TAILQ_REMOVE(&base->hostsdb, victim, next);
mm_free(victim);
}
}
mm_free(base->req_heads);
EVDNS_UNLOCK(base);
EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
mm_free(base);
}
void
evdns_base_free(struct evdns_base *base, int fail_requests)
{
EVDNS_LOCK(base);
evdns_base_free_and_unlock(base, fail_requests);
}
void
evdns_base_clear_host_addresses(struct evdns_base *base)
{
struct hosts_entry *victim;
EVDNS_LOCK(base);
while ((victim = TAILQ_FIRST(&base->hostsdb))) {
TAILQ_REMOVE(&base->hostsdb, victim, next);
mm_free(victim);
}
EVDNS_UNLOCK(base);
}
void
evdns_shutdown(int fail_requests)
{
if (current_base) {
struct evdns_base *b = current_base;
current_base = NULL;
evdns_base_free(b, fail_requests);
}
evdns_log_fn = NULL;
}
static int
evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
{
char *strtok_state;
static const char *const delims = " \t";
char *const addr = strtok_r(line, delims, &strtok_state);
char *hostname, *hash;
struct sockaddr_storage ss;
int socklen = sizeof(ss);
ASSERT_LOCKED(base);
#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
if (!addr || *addr == '#')
return 0;
memset(&ss, 0, sizeof(ss));
if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
return -1;
if (socklen > (int)sizeof(struct sockaddr_in6))
return -1;
if (sockaddr_getport((struct sockaddr*)&ss))
return -1;
while ((hostname = NEXT_TOKEN)) {
struct hosts_entry *he;
size_t namelen;
if ((hash = strchr(hostname, '#'))) {
if (hash == hostname)
return 0;
*hash = '\0';
}
namelen = strlen(hostname);
he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
if (!he)
return -1;
EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
memcpy(&he->addr, &ss, socklen);
memcpy(he->hostname, hostname, namelen+1);
he->addrlen = socklen;
TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
if (hash)
return 0;
}
return 0;
#undef NEXT_TOKEN
}
static int
evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
{
char *str=NULL, *cp, *eol;
size_t len;
int err=0;
ASSERT_LOCKED(base);
if (hosts_fname == NULL ||
(err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
char tmp[64];
strlcpy(tmp, "127.0.0.1 localhost", sizeof(tmp));
evdns_base_parse_hosts_line(base, tmp);
strlcpy(tmp, "::1 localhost", sizeof(tmp));
evdns_base_parse_hosts_line(base, tmp);
return err ? -1 : 0;
}
/* This will break early if there is a NUL in the hosts file.
* Probably not a problem.*/
cp = str;
for (;;) {
eol = strchr(cp, '\n');
if (eol) {
*eol = '\0';
evdns_base_parse_hosts_line(base, cp);
cp = eol+1;
} else {
evdns_base_parse_hosts_line(base, cp);
break;
}
}
mm_free(str);
return 0;
}
int
evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
{
int res;
if (!base)
base = current_base;
EVDNS_LOCK(base);
res = evdns_base_load_hosts_impl(base, hosts_fname);
EVDNS_UNLOCK(base);
return res;
}
/* A single request for a getaddrinfo, either v4 or v6. */
struct getaddrinfo_subrequest {
struct evdns_request *r;
ev_uint32_t type;
};
/* State data used to implement an in-progress getaddrinfo. */
struct evdns_getaddrinfo_request {
struct evdns_base *evdns_base;
/* Copy of the modified 'hints' data that we'll use to build
* answers. */
struct evutil_addrinfo hints;
/* The callback to invoke when we're done */
evdns_getaddrinfo_cb user_cb;
/* User-supplied data to give to the callback. */
void *user_data;
/* The port to use when building sockaddrs. */
ev_uint16_t port;
/* The sub_request for an A record (if any) */
struct getaddrinfo_subrequest ipv4_request;
/* The sub_request for an AAAA record (if any) */
struct getaddrinfo_subrequest ipv6_request;
/* The cname result that we were told (if any) */
char *cname_result;
/* If we have one request answered and one request still inflight,
* then this field holds the answer from the first request... */
struct evutil_addrinfo *pending_result;
/* And this event is a timeout that will tell us to cancel the second
* request if it's taking a long time. */
struct event timeout;
/* And this field holds the error code from the first request... */
int pending_error;
/* If this is set, the user canceled this request. */
unsigned user_canceled : 1;
/* If this is set, the user can no longer cancel this request; we're
* just waiting for the free. */
unsigned request_done : 1;
};
/* Convert an evdns errors to the equivalent getaddrinfo error. */
static int
evdns_err_to_getaddrinfo_err(int e1)
{
/* XXX Do this better! */
if (e1 == DNS_ERR_NONE)
return 0;
else if (e1 == DNS_ERR_NOTEXIST)
return EVUTIL_EAI_NONAME;
else
return EVUTIL_EAI_FAIL;
}
/* Return the more informative of two getaddrinfo errors. */
static int
getaddrinfo_merge_err(int e1, int e2)
{
/* XXXX be cleverer here. */
if (e1 == 0)
return e2;
else
return e1;
}
static void
free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
{
/* DO NOT CALL this if either of the requests is pending. Only once
* both callbacks have been invoked is it safe to free the request */
if (data->pending_result)
evutil_freeaddrinfo(data->pending_result);
if (data->cname_result)
mm_free(data->cname_result);
event_del(&data->timeout);
mm_free(data);
return;
}
static void
add_cname_to_reply(struct evdns_getaddrinfo_request *data,
struct evutil_addrinfo *ai)
{
if (data->cname_result && ai) {
ai->ai_canonname = data->cname_result;
data->cname_result = NULL;
}
}
/* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
* request has finished, but the other one took too long to answer. Pass
* along the answer we got, and cancel the other request.
*/
static void
evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
{
int v4_timedout = 0, v6_timedout = 0;
struct evdns_getaddrinfo_request *data = ptr;
/* Cancel any pending requests, and note which one */
if (data->ipv4_request.r) {
/* XXXX This does nothing if the request's callback is already
* running (pending_cb is set). */
evdns_cancel_request(NULL, data->ipv4_request.r);
v4_timedout = 1;
EVDNS_LOCK(data->evdns_base);
++data->evdns_base->getaddrinfo_ipv4_timeouts;
EVDNS_UNLOCK(data->evdns_base);
}
if (data->ipv6_request.r) {
/* XXXX This does nothing if the request's callback is already
* running (pending_cb is set). */
evdns_cancel_request(NULL, data->ipv6_request.r);
v6_timedout = 1;
EVDNS_LOCK(data->evdns_base);
++data->evdns_base->getaddrinfo_ipv6_timeouts;
EVDNS_UNLOCK(data->evdns_base);
}
/* We only use this timeout callback when we have an answer for
* one address. */
EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
/* Report the outcome of the other request that didn't time out. */
if (data->pending_result) {
add_cname_to_reply(data, data->pending_result);
data->user_cb(0, data->pending_result, data->user_data);
data->pending_result = NULL;
} else {
int e = data->pending_error;
if (!e)
e = EVUTIL_EAI_AGAIN;
data->user_cb(e, NULL, data->user_data);
}
data->user_cb = NULL; /* prevent double-call if evdns callbacks are
* in-progress. XXXX It would be better if this
* weren't necessary. */
if (!v4_timedout && !v6_timedout) {
/* should be impossible? XXXX */
free_getaddrinfo_request(data);
}
}
static int
evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
struct evdns_getaddrinfo_request *data)
{
return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
}
static inline int
evdns_result_is_answer(int result)
{
return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
}
static void
evdns_getaddrinfo_gotresolve(int result, char type, int count,
int ttl, void *addresses, void *arg)
{
int i;
struct getaddrinfo_subrequest *req = arg;
struct getaddrinfo_subrequest *other_req;
struct evdns_getaddrinfo_request *data;
struct evutil_addrinfo *res;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
struct sockaddr *sa;
int socklen, addrlen;
void *addrp;
int err;
int user_canceled;
EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
if (req->type == DNS_IPv4_A) {
data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
other_req = &data->ipv6_request;
} else {
data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
other_req = &data->ipv4_request;
}
/** Called from evdns_base_free() with @fail_requests == 1 */
if (result != DNS_ERR_SHUTDOWN) {
EVDNS_LOCK(data->evdns_base);
if (evdns_result_is_answer(result)) {
if (req->type == DNS_IPv4_A)
++data->evdns_base->getaddrinfo_ipv4_answered;
else
++data->evdns_base->getaddrinfo_ipv6_answered;
}
user_canceled = data->user_canceled;
if (other_req->r == NULL)
data->request_done = 1;
EVDNS_UNLOCK(data->evdns_base);
} else {
data->evdns_base = NULL;
user_canceled = data->user_canceled;
}
req->r = NULL;
if (result == DNS_ERR_CANCEL && ! user_canceled) {
/* Internal cancel request from timeout or internal error.
* we already answered the user. */
if (other_req->r == NULL)
free_getaddrinfo_request(data);
return;
}
if (data->user_cb == NULL) {
/* We already answered. XXXX This shouldn't be needed; see
* comments in evdns_getaddrinfo_timeout_cb */
free_getaddrinfo_request(data);
return;
}
if (result == DNS_ERR_NONE) {
if (count == 0)
err = EVUTIL_EAI_NODATA;
else
err = 0;
} else {
err = evdns_err_to_getaddrinfo_err(result);
}
if (err) {
/* Looks like we got an error. */
if (other_req->r) {
/* The other request is still working; maybe it will
* succeed. */
/* XXXX handle failure from set_timeout */
if (result != DNS_ERR_SHUTDOWN) {
evdns_getaddrinfo_set_timeout(data->evdns_base, data);
}
data->pending_error = err;
return;
}
if (user_canceled) {
data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
} else if (data->pending_result) {
/* If we have an answer waiting, and we weren't
* canceled, ignore this error. */
add_cname_to_reply(data, data->pending_result);
data->user_cb(0, data->pending_result, data->user_data);
data->pending_result = NULL;
} else {
if (data->pending_error)
err = getaddrinfo_merge_err(err,
data->pending_error);
data->user_cb(err, NULL, data->user_data);
}
free_getaddrinfo_request(data);
return;
} else if (user_canceled) {
if (other_req->r) {
/* The other request is still working; let it hit this
* callback with EVUTIL_EAI_CANCEL callback and report
* the failure. */
return;
}
data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
free_getaddrinfo_request(data);
return;
}
/* Looks like we got some answers. We should turn them into addrinfos
* and then either queue those or return them all. */
EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
if (type == DNS_IPv4_A) {
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(data->port);
sa = (struct sockaddr *)&sin;
socklen = sizeof(sin);
addrlen = 4;
addrp = &sin.sin_addr.s_addr;
} else {
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(data->port);
sa = (struct sockaddr *)&sin6;
socklen = sizeof(sin6);
addrlen = 16;
addrp = &sin6.sin6_addr.s6_addr;
}
res = NULL;
for (i=0; i < count; ++i) {
struct evutil_addrinfo *ai;
memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
if (!ai) {
if (other_req->r) {
evdns_cancel_request(NULL, other_req->r);
}
data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
if (res)
evutil_freeaddrinfo(res);
if (other_req->r == NULL)
free_getaddrinfo_request(data);
return;
}
res = evutil_addrinfo_append_(res, ai);
}
if (other_req->r) {
/* The other request is still in progress; wait for it */
/* XXXX handle failure from set_timeout */
evdns_getaddrinfo_set_timeout(data->evdns_base, data);
data->pending_result = res;
return;
} else {
/* The other request is done or never started; append its
* results (if any) and return them. */
if (data->pending_result) {
if (req->type == DNS_IPv4_A)
res = evutil_addrinfo_append_(res,
data->pending_result);
else
res = evutil_addrinfo_append_(
data->pending_result, res);
data->pending_result = NULL;
}
/* Call the user callback. */
add_cname_to_reply(data, res);
data->user_cb(0, res, data->user_data);
/* Free data. */
free_getaddrinfo_request(data);
}
}
static struct hosts_entry *
find_hosts_entry(struct evdns_base *base, const char *hostname,
struct hosts_entry *find_after)
{
struct hosts_entry *e;
if (find_after)
e = TAILQ_NEXT(find_after, next);
else
e = TAILQ_FIRST(&base->hostsdb);
for (; e; e = TAILQ_NEXT(e, next)) {
if (!evutil_ascii_strcasecmp(e->hostname, hostname))
return e;
}
return NULL;
}
static int
evdns_getaddrinfo_fromhosts(struct evdns_base *base,
const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
struct evutil_addrinfo **res)
{
int n_found = 0;
struct hosts_entry *e;
struct evutil_addrinfo *ai=NULL;
int f = hints->ai_family;
EVDNS_LOCK(base);
for (e = find_hosts_entry(base, nodename, NULL); e;
e = find_hosts_entry(base, nodename, e)) {
struct evutil_addrinfo *ai_new;
++n_found;
if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
(e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
continue;
ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
if (!ai_new) {
n_found = 0;
goto out;
}
sockaddr_setport(ai_new->ai_addr, port);
ai = evutil_addrinfo_append_(ai, ai_new);
}
EVDNS_UNLOCK(base);
out:
if (n_found) {
/* Note that we return an empty answer if we found entries for
* this hostname but none were of the right address type. */
*res = ai;
return 0;
} else {
if (ai)
evutil_freeaddrinfo(ai);
return -1;
}
}
struct evdns_getaddrinfo_request *
evdns_getaddrinfo(struct evdns_base *dns_base,
const char *nodename, const char *servname,
const struct evutil_addrinfo *hints_in,
evdns_getaddrinfo_cb cb, void *arg)
{
struct evdns_getaddrinfo_request *data;
struct evutil_addrinfo hints;
struct evutil_addrinfo *res = NULL;
int err;
int port = 0;
int want_cname = 0;
if (!dns_base) {
dns_base = current_base;
if (!dns_base) {
log(EVDNS_LOG_WARN,
"Call to getaddrinfo_async with no "
"evdns_base configured.");
cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
return NULL;
}
}
/* If we _must_ answer this immediately, do so. */
if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
res = NULL;
err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
cb(err, res, arg);
return NULL;
}
if (hints_in) {
memcpy(&hints, hints_in, sizeof(hints));
} else {
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
}
evutil_adjust_hints_for_addrconfig_(&hints);
/* Now try to see if we _can_ answer immediately. */
/* (It would be nice to do this by calling getaddrinfo directly, with
* AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
* a reliable way to distinguish the "that wasn't a numeric host!" case
* from any other EAI_NONAME cases.) */
err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
if (err != EVUTIL_EAI_NEED_RESOLVE) {
cb(err, res, arg);
return NULL;
}
/* If there is an entry in the hosts file, we should give it now. */
if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
cb(0, res, arg);
return NULL;
}
/* Okay, things are serious now. We're going to need to actually
* launch a request.
*/
data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
if (!data) {
cb(EVUTIL_EAI_MEMORY, NULL, arg);
return NULL;
}
memcpy(&data->hints, &hints, sizeof(data->hints));
data->port = (ev_uint16_t)port;
data->ipv4_request.type = DNS_IPv4_A;
data->ipv6_request.type = DNS_IPv6_AAAA;
data->user_cb = cb;
data->user_data = arg;
data->evdns_base = dns_base;
want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
/* If we are asked for a PF_UNSPEC address, we launch two requests in
* parallel: one for an A address and one for an AAAA address. We
* can't send just one request, since many servers only answer one
* question per DNS request.
*
* Once we have the answer to one request, we allow for a short
* timeout before we report it, to see if the other one arrives. If
* they both show up in time, then we report both the answers.
*
* If too many addresses of one type time out or fail, we should stop
* launching those requests. (XXX we don't do that yet.)
*/
if (hints.ai_family != PF_INET6) {
log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
nodename, &data->ipv4_request);
data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
nodename, 0, evdns_getaddrinfo_gotresolve,
&data->ipv4_request);
if (want_cname && data->ipv4_request.r)
data->ipv4_request.r->current_req->put_cname_in_ptr =
&data->cname_result;
}
if (hints.ai_family != PF_INET) {
log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
nodename, &data->ipv6_request);
data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
nodename, 0, evdns_getaddrinfo_gotresolve,
&data->ipv6_request);
if (want_cname && data->ipv6_request.r)
data->ipv6_request.r->current_req->put_cname_in_ptr =
&data->cname_result;
}
evtimer_assign(&data->timeout, dns_base->event_base,
evdns_getaddrinfo_timeout_cb, data);
if (data->ipv4_request.r || data->ipv6_request.r) {
return data;
} else {
mm_free(data);
cb(EVUTIL_EAI_FAIL, NULL, arg);
return NULL;
}
}
void
evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
{
EVDNS_LOCK(data->evdns_base);
if (data->request_done) {
EVDNS_UNLOCK(data->evdns_base);
return;
}
event_del(&data->timeout);
data->user_canceled = 1;
if (data->ipv4_request.r)
evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
if (data->ipv6_request.r)
evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
EVDNS_UNLOCK(data->evdns_base);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4840_0 |
crossvul-cpp_data_good_3254_1 | /*
* Routines having to do with the 'struct sk_buff' memory handlers.
*
* Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
* Florian La Roche <rzsfl@rz.uni-sb.de>
*
* Fixes:
* Alan Cox : Fixed the worst of the load
* balancer bugs.
* Dave Platt : Interrupt stacking fix.
* Richard Kooijman : Timestamp fixes.
* Alan Cox : Changed buffer format.
* Alan Cox : destructor hook for AF_UNIX etc.
* Linus Torvalds : Better skb_clone.
* Alan Cox : Added skb_copy.
* Alan Cox : Added all the changed routines Linus
* only put in the headers
* Ray VanTassle : Fixed --skb->lock in free
* Alan Cox : skb_copy copy arp field
* Andi Kleen : slabified it.
* Robert Olsson : Removed skb_head_pool
*
* NOTE:
* The __skb_ routines should be called with interrupts
* disabled, or you better be *real* sure that the operation is atomic
* with respect to whatever list is being frobbed (e.g. via lock_sock()
* or via disabling bottom half handlers, etc).
*
* 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.
*/
/*
* The functions in this file will not compile correctly with gcc 2.4.x
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/kmemcheck.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/sctp.h>
#include <linux/netdevice.h>
#ifdef CONFIG_NET_CLS_ACT
#include <net/pkt_sched.h>
#endif
#include <linux/string.h>
#include <linux/skbuff.h>
#include <linux/splice.h>
#include <linux/cache.h>
#include <linux/rtnetlink.h>
#include <linux/init.h>
#include <linux/scatterlist.h>
#include <linux/errqueue.h>
#include <linux/prefetch.h>
#include <linux/if_vlan.h>
#include <net/protocol.h>
#include <net/dst.h>
#include <net/sock.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <net/xfrm.h>
#include <linux/uaccess.h>
#include <trace/events/skb.h>
#include <linux/highmem.h>
#include <linux/capability.h>
#include <linux/user_namespace.h>
struct kmem_cache *skbuff_head_cache __read_mostly;
static struct kmem_cache *skbuff_fclone_cache __read_mostly;
int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
EXPORT_SYMBOL(sysctl_max_skb_frags);
/**
* skb_panic - private function for out-of-line support
* @skb: buffer
* @sz: size
* @addr: address
* @msg: skb_over_panic or skb_under_panic
*
* Out-of-line support for skb_put() and skb_push().
* Called via the wrapper skb_over_panic() or skb_under_panic().
* Keep out of line to prevent kernel bloat.
* __builtin_return_address is not used because it is not always reliable.
*/
static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
const char msg[])
{
pr_emerg("%s: text:%p len:%d put:%d head:%p data:%p tail:%#lx end:%#lx dev:%s\n",
msg, addr, skb->len, sz, skb->head, skb->data,
(unsigned long)skb->tail, (unsigned long)skb->end,
skb->dev ? skb->dev->name : "<NULL>");
BUG();
}
static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
{
skb_panic(skb, sz, addr, __func__);
}
static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
{
skb_panic(skb, sz, addr, __func__);
}
/*
* kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
* the caller if emergency pfmemalloc reserves are being used. If it is and
* the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
* may be used. Otherwise, the packet data may be discarded until enough
* memory is free
*/
#define kmalloc_reserve(size, gfp, node, pfmemalloc) \
__kmalloc_reserve(size, gfp, node, _RET_IP_, pfmemalloc)
static void *__kmalloc_reserve(size_t size, gfp_t flags, int node,
unsigned long ip, bool *pfmemalloc)
{
void *obj;
bool ret_pfmemalloc = false;
/*
* Try a regular allocation, when that fails and we're not entitled
* to the reserves, fail.
*/
obj = kmalloc_node_track_caller(size,
flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
node);
if (obj || !(gfp_pfmemalloc_allowed(flags)))
goto out;
/* Try again but now we are using pfmemalloc reserves */
ret_pfmemalloc = true;
obj = kmalloc_node_track_caller(size, flags, node);
out:
if (pfmemalloc)
*pfmemalloc = ret_pfmemalloc;
return obj;
}
/* Allocate a new skbuff. We do this ourselves so we can fill in a few
* 'private' fields and also do memory statistics to find all the
* [BEEP] leaks.
*
*/
struct sk_buff *__alloc_skb_head(gfp_t gfp_mask, int node)
{
struct sk_buff *skb;
/* Get the HEAD */
skb = kmem_cache_alloc_node(skbuff_head_cache,
gfp_mask & ~__GFP_DMA, node);
if (!skb)
goto out;
/*
* Only clear those fields we need to clear, not those that we will
* actually initialise below. Hence, don't put any more fields after
* the tail pointer in struct sk_buff!
*/
memset(skb, 0, offsetof(struct sk_buff, tail));
skb->head = NULL;
skb->truesize = sizeof(struct sk_buff);
atomic_set(&skb->users, 1);
skb->mac_header = (typeof(skb->mac_header))~0U;
out:
return skb;
}
/**
* __alloc_skb - allocate a network buffer
* @size: size to allocate
* @gfp_mask: allocation mask
* @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
* instead of head cache and allocate a cloned (child) skb.
* If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
* allocations in case the data is required for writeback
* @node: numa node to allocate memory on
*
* Allocate a new &sk_buff. The returned buffer has no headroom and a
* tail room of at least size bytes. The object has a reference count
* of one. The return is the buffer. On a failure the return is %NULL.
*
* Buffers may only be allocated from interrupts using a @gfp_mask of
* %GFP_ATOMIC.
*/
struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
int flags, int node)
{
struct kmem_cache *cache;
struct skb_shared_info *shinfo;
struct sk_buff *skb;
u8 *data;
bool pfmemalloc;
cache = (flags & SKB_ALLOC_FCLONE)
? skbuff_fclone_cache : skbuff_head_cache;
if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
gfp_mask |= __GFP_MEMALLOC;
/* Get the HEAD */
skb = kmem_cache_alloc_node(cache, gfp_mask & ~__GFP_DMA, node);
if (!skb)
goto out;
prefetchw(skb);
/* We do our best to align skb_shared_info on a separate cache
* line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
* aligned memory blocks, unless SLUB/SLAB debug is enabled.
* Both skb->head and skb_shared_info are cache line aligned.
*/
size = SKB_DATA_ALIGN(size);
size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
if (!data)
goto nodata;
/* kmalloc(size) might give us more room than requested.
* Put skb_shared_info exactly at the end of allocated zone,
* to allow max possible filling before reallocation.
*/
size = SKB_WITH_OVERHEAD(ksize(data));
prefetchw(data + size);
/*
* Only clear those fields we need to clear, not those that we will
* actually initialise below. Hence, don't put any more fields after
* the tail pointer in struct sk_buff!
*/
memset(skb, 0, offsetof(struct sk_buff, tail));
/* Account for allocated memory : skb + skb->head */
skb->truesize = SKB_TRUESIZE(size);
skb->pfmemalloc = pfmemalloc;
atomic_set(&skb->users, 1);
skb->head = data;
skb->data = data;
skb_reset_tail_pointer(skb);
skb->end = skb->tail + size;
skb->mac_header = (typeof(skb->mac_header))~0U;
skb->transport_header = (typeof(skb->transport_header))~0U;
/* make sure we initialize shinfo sequentially */
shinfo = skb_shinfo(skb);
memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
atomic_set(&shinfo->dataref, 1);
kmemcheck_annotate_variable(shinfo->destructor_arg);
if (flags & SKB_ALLOC_FCLONE) {
struct sk_buff_fclones *fclones;
fclones = container_of(skb, struct sk_buff_fclones, skb1);
kmemcheck_annotate_bitfield(&fclones->skb2, flags1);
skb->fclone = SKB_FCLONE_ORIG;
atomic_set(&fclones->fclone_ref, 1);
fclones->skb2.fclone = SKB_FCLONE_CLONE;
}
out:
return skb;
nodata:
kmem_cache_free(cache, skb);
skb = NULL;
goto out;
}
EXPORT_SYMBOL(__alloc_skb);
/**
* __build_skb - build a network buffer
* @data: data buffer provided by caller
* @frag_size: size of data, or 0 if head was kmalloced
*
* Allocate a new &sk_buff. Caller provides space holding head and
* skb_shared_info. @data must have been allocated by kmalloc() only if
* @frag_size is 0, otherwise data should come from the page allocator
* or vmalloc()
* The return is the new skb buffer.
* On a failure the return is %NULL, and @data is not freed.
* Notes :
* Before IO, driver allocates only data buffer where NIC put incoming frame
* Driver should add room at head (NET_SKB_PAD) and
* MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
* After IO, driver calls build_skb(), to allocate sk_buff and populate it
* before giving packet to stack.
* RX rings only contains data buffers, not full skbs.
*/
struct sk_buff *__build_skb(void *data, unsigned int frag_size)
{
struct skb_shared_info *shinfo;
struct sk_buff *skb;
unsigned int size = frag_size ? : ksize(data);
skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
if (!skb)
return NULL;
size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
memset(skb, 0, offsetof(struct sk_buff, tail));
skb->truesize = SKB_TRUESIZE(size);
atomic_set(&skb->users, 1);
skb->head = data;
skb->data = data;
skb_reset_tail_pointer(skb);
skb->end = skb->tail + size;
skb->mac_header = (typeof(skb->mac_header))~0U;
skb->transport_header = (typeof(skb->transport_header))~0U;
/* make sure we initialize shinfo sequentially */
shinfo = skb_shinfo(skb);
memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
atomic_set(&shinfo->dataref, 1);
kmemcheck_annotate_variable(shinfo->destructor_arg);
return skb;
}
/* build_skb() is wrapper over __build_skb(), that specifically
* takes care of skb->head and skb->pfmemalloc
* This means that if @frag_size is not zero, then @data must be backed
* by a page fragment, not kmalloc() or vmalloc()
*/
struct sk_buff *build_skb(void *data, unsigned int frag_size)
{
struct sk_buff *skb = __build_skb(data, frag_size);
if (skb && frag_size) {
skb->head_frag = 1;
if (page_is_pfmemalloc(virt_to_head_page(data)))
skb->pfmemalloc = 1;
}
return skb;
}
EXPORT_SYMBOL(build_skb);
#define NAPI_SKB_CACHE_SIZE 64
struct napi_alloc_cache {
struct page_frag_cache page;
unsigned int skb_count;
void *skb_cache[NAPI_SKB_CACHE_SIZE];
};
static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
static void *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask)
{
struct page_frag_cache *nc;
unsigned long flags;
void *data;
local_irq_save(flags);
nc = this_cpu_ptr(&netdev_alloc_cache);
data = page_frag_alloc(nc, fragsz, gfp_mask);
local_irq_restore(flags);
return data;
}
/**
* netdev_alloc_frag - allocate a page fragment
* @fragsz: fragment size
*
* Allocates a frag from a page for receive buffer.
* Uses GFP_ATOMIC allocations.
*/
void *netdev_alloc_frag(unsigned int fragsz)
{
return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD);
}
EXPORT_SYMBOL(netdev_alloc_frag);
static void *__napi_alloc_frag(unsigned int fragsz, gfp_t gfp_mask)
{
struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
return page_frag_alloc(&nc->page, fragsz, gfp_mask);
}
void *napi_alloc_frag(unsigned int fragsz)
{
return __napi_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD);
}
EXPORT_SYMBOL(napi_alloc_frag);
/**
* __netdev_alloc_skb - allocate an skbuff for rx on a specific device
* @dev: network device to receive on
* @len: length to allocate
* @gfp_mask: get_free_pages mask, passed to alloc_skb
*
* Allocate a new &sk_buff and assign it a usage count of one. The
* buffer has NET_SKB_PAD headroom built in. Users should allocate
* the headroom they think they need without accounting for the
* built in space. The built in space is used for optimisations.
*
* %NULL is returned if there is no free memory.
*/
struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
gfp_t gfp_mask)
{
struct page_frag_cache *nc;
unsigned long flags;
struct sk_buff *skb;
bool pfmemalloc;
void *data;
len += NET_SKB_PAD;
if ((len > SKB_WITH_OVERHEAD(PAGE_SIZE)) ||
(gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
if (!skb)
goto skb_fail;
goto skb_success;
}
len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
len = SKB_DATA_ALIGN(len);
if (sk_memalloc_socks())
gfp_mask |= __GFP_MEMALLOC;
local_irq_save(flags);
nc = this_cpu_ptr(&netdev_alloc_cache);
data = page_frag_alloc(nc, len, gfp_mask);
pfmemalloc = nc->pfmemalloc;
local_irq_restore(flags);
if (unlikely(!data))
return NULL;
skb = __build_skb(data, len);
if (unlikely(!skb)) {
skb_free_frag(data);
return NULL;
}
/* use OR instead of assignment to avoid clearing of bits in mask */
if (pfmemalloc)
skb->pfmemalloc = 1;
skb->head_frag = 1;
skb_success:
skb_reserve(skb, NET_SKB_PAD);
skb->dev = dev;
skb_fail:
return skb;
}
EXPORT_SYMBOL(__netdev_alloc_skb);
/**
* __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
* @napi: napi instance this buffer was allocated for
* @len: length to allocate
* @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
*
* Allocate a new sk_buff for use in NAPI receive. This buffer will
* attempt to allocate the head from a special reserved region used
* only for NAPI Rx allocation. By doing this we can save several
* CPU cycles by avoiding having to disable and re-enable IRQs.
*
* %NULL is returned if there is no free memory.
*/
struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
gfp_t gfp_mask)
{
struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
struct sk_buff *skb;
void *data;
len += NET_SKB_PAD + NET_IP_ALIGN;
if ((len > SKB_WITH_OVERHEAD(PAGE_SIZE)) ||
(gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
if (!skb)
goto skb_fail;
goto skb_success;
}
len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
len = SKB_DATA_ALIGN(len);
if (sk_memalloc_socks())
gfp_mask |= __GFP_MEMALLOC;
data = page_frag_alloc(&nc->page, len, gfp_mask);
if (unlikely(!data))
return NULL;
skb = __build_skb(data, len);
if (unlikely(!skb)) {
skb_free_frag(data);
return NULL;
}
/* use OR instead of assignment to avoid clearing of bits in mask */
if (nc->page.pfmemalloc)
skb->pfmemalloc = 1;
skb->head_frag = 1;
skb_success:
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
skb->dev = napi->dev;
skb_fail:
return skb;
}
EXPORT_SYMBOL(__napi_alloc_skb);
void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
int size, unsigned int truesize)
{
skb_fill_page_desc(skb, i, page, off, size);
skb->len += size;
skb->data_len += size;
skb->truesize += truesize;
}
EXPORT_SYMBOL(skb_add_rx_frag);
void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
unsigned int truesize)
{
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
skb_frag_size_add(frag, size);
skb->len += size;
skb->data_len += size;
skb->truesize += truesize;
}
EXPORT_SYMBOL(skb_coalesce_rx_frag);
static void skb_drop_list(struct sk_buff **listp)
{
kfree_skb_list(*listp);
*listp = NULL;
}
static inline void skb_drop_fraglist(struct sk_buff *skb)
{
skb_drop_list(&skb_shinfo(skb)->frag_list);
}
static void skb_clone_fraglist(struct sk_buff *skb)
{
struct sk_buff *list;
skb_walk_frags(skb, list)
skb_get(list);
}
static void skb_free_head(struct sk_buff *skb)
{
unsigned char *head = skb->head;
if (skb->head_frag)
skb_free_frag(head);
else
kfree(head);
}
static void skb_release_data(struct sk_buff *skb)
{
struct skb_shared_info *shinfo = skb_shinfo(skb);
int i;
if (skb->cloned &&
atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
&shinfo->dataref))
return;
for (i = 0; i < shinfo->nr_frags; i++)
__skb_frag_unref(&shinfo->frags[i]);
/*
* If skb buf is from userspace, we need to notify the caller
* the lower device DMA has done;
*/
if (shinfo->tx_flags & SKBTX_DEV_ZEROCOPY) {
struct ubuf_info *uarg;
uarg = shinfo->destructor_arg;
if (uarg->callback)
uarg->callback(uarg, true);
}
if (shinfo->frag_list)
kfree_skb_list(shinfo->frag_list);
skb_free_head(skb);
}
/*
* Free an skbuff by memory without cleaning the state.
*/
static void kfree_skbmem(struct sk_buff *skb)
{
struct sk_buff_fclones *fclones;
switch (skb->fclone) {
case SKB_FCLONE_UNAVAILABLE:
kmem_cache_free(skbuff_head_cache, skb);
return;
case SKB_FCLONE_ORIG:
fclones = container_of(skb, struct sk_buff_fclones, skb1);
/* We usually free the clone (TX completion) before original skb
* This test would have no chance to be true for the clone,
* while here, branch prediction will be good.
*/
if (atomic_read(&fclones->fclone_ref) == 1)
goto fastpath;
break;
default: /* SKB_FCLONE_CLONE */
fclones = container_of(skb, struct sk_buff_fclones, skb2);
break;
}
if (!atomic_dec_and_test(&fclones->fclone_ref))
return;
fastpath:
kmem_cache_free(skbuff_fclone_cache, fclones);
}
static void skb_release_head_state(struct sk_buff *skb)
{
skb_dst_drop(skb);
#ifdef CONFIG_XFRM
secpath_put(skb->sp);
#endif
if (skb->destructor) {
WARN_ON(in_irq());
skb->destructor(skb);
}
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
nf_conntrack_put(skb_nfct(skb));
#endif
#if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
nf_bridge_put(skb->nf_bridge);
#endif
}
/* Free everything but the sk_buff shell. */
static void skb_release_all(struct sk_buff *skb)
{
skb_release_head_state(skb);
if (likely(skb->head))
skb_release_data(skb);
}
/**
* __kfree_skb - private function
* @skb: buffer
*
* Free an sk_buff. Release anything attached to the buffer.
* Clean the state. This is an internal helper function. Users should
* always call kfree_skb
*/
void __kfree_skb(struct sk_buff *skb)
{
skb_release_all(skb);
kfree_skbmem(skb);
}
EXPORT_SYMBOL(__kfree_skb);
/**
* kfree_skb - free an sk_buff
* @skb: buffer to free
*
* Drop a reference to the buffer and free it if the usage count has
* hit zero.
*/
void kfree_skb(struct sk_buff *skb)
{
if (unlikely(!skb))
return;
if (likely(atomic_read(&skb->users) == 1))
smp_rmb();
else if (likely(!atomic_dec_and_test(&skb->users)))
return;
trace_kfree_skb(skb, __builtin_return_address(0));
__kfree_skb(skb);
}
EXPORT_SYMBOL(kfree_skb);
void kfree_skb_list(struct sk_buff *segs)
{
while (segs) {
struct sk_buff *next = segs->next;
kfree_skb(segs);
segs = next;
}
}
EXPORT_SYMBOL(kfree_skb_list);
/**
* skb_tx_error - report an sk_buff xmit error
* @skb: buffer that triggered an error
*
* Report xmit error if a device callback is tracking this skb.
* skb must be freed afterwards.
*/
void skb_tx_error(struct sk_buff *skb)
{
if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
struct ubuf_info *uarg;
uarg = skb_shinfo(skb)->destructor_arg;
if (uarg->callback)
uarg->callback(uarg, false);
skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
}
}
EXPORT_SYMBOL(skb_tx_error);
/**
* consume_skb - free an skbuff
* @skb: buffer to free
*
* Drop a ref to the buffer and free it if the usage count has hit zero
* Functions identically to kfree_skb, but kfree_skb assumes that the frame
* is being dropped after a failure and notes that
*/
void consume_skb(struct sk_buff *skb)
{
if (unlikely(!skb))
return;
if (likely(atomic_read(&skb->users) == 1))
smp_rmb();
else if (likely(!atomic_dec_and_test(&skb->users)))
return;
trace_consume_skb(skb);
__kfree_skb(skb);
}
EXPORT_SYMBOL(consume_skb);
void __kfree_skb_flush(void)
{
struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
/* flush skb_cache if containing objects */
if (nc->skb_count) {
kmem_cache_free_bulk(skbuff_head_cache, nc->skb_count,
nc->skb_cache);
nc->skb_count = 0;
}
}
static inline void _kfree_skb_defer(struct sk_buff *skb)
{
struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
/* drop skb->head and call any destructors for packet */
skb_release_all(skb);
/* record skb to CPU local list */
nc->skb_cache[nc->skb_count++] = skb;
#ifdef CONFIG_SLUB
/* SLUB writes into objects when freeing */
prefetchw(skb);
#endif
/* flush skb_cache if it is filled */
if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_SIZE,
nc->skb_cache);
nc->skb_count = 0;
}
}
void __kfree_skb_defer(struct sk_buff *skb)
{
_kfree_skb_defer(skb);
}
void napi_consume_skb(struct sk_buff *skb, int budget)
{
if (unlikely(!skb))
return;
/* Zero budget indicate non-NAPI context called us, like netpoll */
if (unlikely(!budget)) {
dev_consume_skb_any(skb);
return;
}
if (likely(atomic_read(&skb->users) == 1))
smp_rmb();
else if (likely(!atomic_dec_and_test(&skb->users)))
return;
/* if reaching here SKB is ready to free */
trace_consume_skb(skb);
/* if SKB is a clone, don't handle this case */
if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
__kfree_skb(skb);
return;
}
_kfree_skb_defer(skb);
}
EXPORT_SYMBOL(napi_consume_skb);
/* Make sure a field is enclosed inside headers_start/headers_end section */
#define CHECK_SKB_FIELD(field) \
BUILD_BUG_ON(offsetof(struct sk_buff, field) < \
offsetof(struct sk_buff, headers_start)); \
BUILD_BUG_ON(offsetof(struct sk_buff, field) > \
offsetof(struct sk_buff, headers_end)); \
static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
{
new->tstamp = old->tstamp;
/* We do not copy old->sk */
new->dev = old->dev;
memcpy(new->cb, old->cb, sizeof(old->cb));
skb_dst_copy(new, old);
#ifdef CONFIG_XFRM
new->sp = secpath_get(old->sp);
#endif
__nf_copy(new, old, false);
/* Note : this field could be in headers_start/headers_end section
* It is not yet because we do not want to have a 16 bit hole
*/
new->queue_mapping = old->queue_mapping;
memcpy(&new->headers_start, &old->headers_start,
offsetof(struct sk_buff, headers_end) -
offsetof(struct sk_buff, headers_start));
CHECK_SKB_FIELD(protocol);
CHECK_SKB_FIELD(csum);
CHECK_SKB_FIELD(hash);
CHECK_SKB_FIELD(priority);
CHECK_SKB_FIELD(skb_iif);
CHECK_SKB_FIELD(vlan_proto);
CHECK_SKB_FIELD(vlan_tci);
CHECK_SKB_FIELD(transport_header);
CHECK_SKB_FIELD(network_header);
CHECK_SKB_FIELD(mac_header);
CHECK_SKB_FIELD(inner_protocol);
CHECK_SKB_FIELD(inner_transport_header);
CHECK_SKB_FIELD(inner_network_header);
CHECK_SKB_FIELD(inner_mac_header);
CHECK_SKB_FIELD(mark);
#ifdef CONFIG_NETWORK_SECMARK
CHECK_SKB_FIELD(secmark);
#endif
#ifdef CONFIG_NET_RX_BUSY_POLL
CHECK_SKB_FIELD(napi_id);
#endif
#ifdef CONFIG_XPS
CHECK_SKB_FIELD(sender_cpu);
#endif
#ifdef CONFIG_NET_SCHED
CHECK_SKB_FIELD(tc_index);
#endif
}
/*
* You should not add any new code to this function. Add it to
* __copy_skb_header above instead.
*/
static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
{
#define C(x) n->x = skb->x
n->next = n->prev = NULL;
n->sk = NULL;
__copy_skb_header(n, skb);
C(len);
C(data_len);
C(mac_len);
n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
n->cloned = 1;
n->nohdr = 0;
n->destructor = NULL;
C(tail);
C(end);
C(head);
C(head_frag);
C(data);
C(truesize);
atomic_set(&n->users, 1);
atomic_inc(&(skb_shinfo(skb)->dataref));
skb->cloned = 1;
return n;
#undef C
}
/**
* skb_morph - morph one skb into another
* @dst: the skb to receive the contents
* @src: the skb to supply the contents
*
* This is identical to skb_clone except that the target skb is
* supplied by the user.
*
* The target skb is returned upon exit.
*/
struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
{
skb_release_all(dst);
return __skb_clone(dst, src);
}
EXPORT_SYMBOL_GPL(skb_morph);
/**
* skb_copy_ubufs - copy userspace skb frags buffers to kernel
* @skb: the skb to modify
* @gfp_mask: allocation priority
*
* This must be called on SKBTX_DEV_ZEROCOPY skb.
* It will copy all frags into kernel and drop the reference
* to userspace pages.
*
* If this function is called from an interrupt gfp_mask() must be
* %GFP_ATOMIC.
*
* Returns 0 on success or a negative error code on failure
* to allocate kernel memory to copy to.
*/
int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
{
int i;
int num_frags = skb_shinfo(skb)->nr_frags;
struct page *page, *head = NULL;
struct ubuf_info *uarg = skb_shinfo(skb)->destructor_arg;
for (i = 0; i < num_frags; i++) {
u8 *vaddr;
skb_frag_t *f = &skb_shinfo(skb)->frags[i];
page = alloc_page(gfp_mask);
if (!page) {
while (head) {
struct page *next = (struct page *)page_private(head);
put_page(head);
head = next;
}
return -ENOMEM;
}
vaddr = kmap_atomic(skb_frag_page(f));
memcpy(page_address(page),
vaddr + f->page_offset, skb_frag_size(f));
kunmap_atomic(vaddr);
set_page_private(page, (unsigned long)head);
head = page;
}
/* skb frags release userspace buffers */
for (i = 0; i < num_frags; i++)
skb_frag_unref(skb, i);
uarg->callback(uarg, false);
/* skb frags point to kernel buffers */
for (i = num_frags - 1; i >= 0; i--) {
__skb_fill_page_desc(skb, i, head, 0,
skb_shinfo(skb)->frags[i].size);
head = (struct page *)page_private(head);
}
skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
return 0;
}
EXPORT_SYMBOL_GPL(skb_copy_ubufs);
/**
* skb_clone - duplicate an sk_buff
* @skb: buffer to clone
* @gfp_mask: allocation priority
*
* Duplicate an &sk_buff. The new one is not owned by a socket. Both
* copies share the same packet data but not structure. The new
* buffer has a reference count of 1. If the allocation fails the
* function returns %NULL otherwise the new buffer is returned.
*
* If this function is called from an interrupt gfp_mask() must be
* %GFP_ATOMIC.
*/
struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
{
struct sk_buff_fclones *fclones = container_of(skb,
struct sk_buff_fclones,
skb1);
struct sk_buff *n;
if (skb_orphan_frags(skb, gfp_mask))
return NULL;
if (skb->fclone == SKB_FCLONE_ORIG &&
atomic_read(&fclones->fclone_ref) == 1) {
n = &fclones->skb2;
atomic_set(&fclones->fclone_ref, 2);
} else {
if (skb_pfmemalloc(skb))
gfp_mask |= __GFP_MEMALLOC;
n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
if (!n)
return NULL;
kmemcheck_annotate_bitfield(n, flags1);
n->fclone = SKB_FCLONE_UNAVAILABLE;
}
return __skb_clone(n, skb);
}
EXPORT_SYMBOL(skb_clone);
static void skb_headers_offset_update(struct sk_buff *skb, int off)
{
/* Only adjust this if it actually is csum_start rather than csum */
if (skb->ip_summed == CHECKSUM_PARTIAL)
skb->csum_start += off;
/* {transport,network,mac}_header and tail are relative to skb->head */
skb->transport_header += off;
skb->network_header += off;
if (skb_mac_header_was_set(skb))
skb->mac_header += off;
skb->inner_transport_header += off;
skb->inner_network_header += off;
skb->inner_mac_header += off;
}
static void copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
{
__copy_skb_header(new, old);
skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
}
static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
{
if (skb_pfmemalloc(skb))
return SKB_ALLOC_RX;
return 0;
}
/**
* skb_copy - create private copy of an sk_buff
* @skb: buffer to copy
* @gfp_mask: allocation priority
*
* Make a copy of both an &sk_buff and its data. This is used when the
* caller wishes to modify the data and needs a private copy of the
* data to alter. Returns %NULL on failure or the pointer to the buffer
* on success. The returned buffer has a reference count of 1.
*
* As by-product this function converts non-linear &sk_buff to linear
* one, so that &sk_buff becomes completely private and caller is allowed
* to modify all the data of returned buffer. This means that this
* function is not recommended for use in circumstances when only
* header is going to be modified. Use pskb_copy() instead.
*/
struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
{
int headerlen = skb_headroom(skb);
unsigned int size = skb_end_offset(skb) + skb->data_len;
struct sk_buff *n = __alloc_skb(size, gfp_mask,
skb_alloc_rx_flag(skb), NUMA_NO_NODE);
if (!n)
return NULL;
/* Set the data pointer */
skb_reserve(n, headerlen);
/* Set the tail pointer and length */
skb_put(n, skb->len);
if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len))
BUG();
copy_skb_header(n, skb);
return n;
}
EXPORT_SYMBOL(skb_copy);
/**
* __pskb_copy_fclone - create copy of an sk_buff with private head.
* @skb: buffer to copy
* @headroom: headroom of new skb
* @gfp_mask: allocation priority
* @fclone: if true allocate the copy of the skb from the fclone
* cache instead of the head cache; it is recommended to set this
* to true for the cases where the copy will likely be cloned
*
* Make a copy of both an &sk_buff and part of its data, located
* in header. Fragmented data remain shared. This is used when
* the caller wishes to modify only header of &sk_buff and needs
* private copy of the header to alter. Returns %NULL on failure
* or the pointer to the buffer on success.
* The returned buffer has a reference count of 1.
*/
struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
gfp_t gfp_mask, bool fclone)
{
unsigned int size = skb_headlen(skb) + headroom;
int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
if (!n)
goto out;
/* Set the data pointer */
skb_reserve(n, headroom);
/* Set the tail pointer and length */
skb_put(n, skb_headlen(skb));
/* Copy the bytes */
skb_copy_from_linear_data(skb, n->data, n->len);
n->truesize += skb->data_len;
n->data_len = skb->data_len;
n->len = skb->len;
if (skb_shinfo(skb)->nr_frags) {
int i;
if (skb_orphan_frags(skb, gfp_mask)) {
kfree_skb(n);
n = NULL;
goto out;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
skb_frag_ref(skb, i);
}
skb_shinfo(n)->nr_frags = i;
}
if (skb_has_frag_list(skb)) {
skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
skb_clone_fraglist(n);
}
copy_skb_header(n, skb);
out:
return n;
}
EXPORT_SYMBOL(__pskb_copy_fclone);
/**
* pskb_expand_head - reallocate header of &sk_buff
* @skb: buffer to reallocate
* @nhead: room to add at head
* @ntail: room to add at tail
* @gfp_mask: allocation priority
*
* Expands (or creates identical copy, if @nhead and @ntail are zero)
* header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
* reference count of 1. Returns zero in the case of success or error,
* if expansion failed. In the last case, &sk_buff is not changed.
*
* All the pointers pointing into skb header may change and must be
* reloaded after call to this function.
*/
int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
gfp_t gfp_mask)
{
int i, osize = skb_end_offset(skb);
int size = osize + nhead + ntail;
long off;
u8 *data;
BUG_ON(nhead < 0);
if (skb_shared(skb))
BUG();
size = SKB_DATA_ALIGN(size);
if (skb_pfmemalloc(skb))
gfp_mask |= __GFP_MEMALLOC;
data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
gfp_mask, NUMA_NO_NODE, NULL);
if (!data)
goto nodata;
size = SKB_WITH_OVERHEAD(ksize(data));
/* Copy only real data... and, alas, header. This should be
* optimized for the cases when header is void.
*/
memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
memcpy((struct skb_shared_info *)(data + size),
skb_shinfo(skb),
offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
/*
* if shinfo is shared we must drop the old head gracefully, but if it
* is not we can just drop the old head and let the existing refcount
* be since all we did is relocate the values
*/
if (skb_cloned(skb)) {
/* copy this zero copy skb frags */
if (skb_orphan_frags(skb, gfp_mask))
goto nofrags;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_frag_ref(skb, i);
if (skb_has_frag_list(skb))
skb_clone_fraglist(skb);
skb_release_data(skb);
} else {
skb_free_head(skb);
}
off = (data + nhead) - skb->head;
skb->head = data;
skb->head_frag = 0;
skb->data += off;
#ifdef NET_SKBUFF_DATA_USES_OFFSET
skb->end = size;
off = nhead;
#else
skb->end = skb->head + size;
#endif
skb->tail += off;
skb_headers_offset_update(skb, nhead);
skb->cloned = 0;
skb->hdr_len = 0;
skb->nohdr = 0;
atomic_set(&skb_shinfo(skb)->dataref, 1);
/* It is not generally safe to change skb->truesize.
* For the moment, we really care of rx path, or
* when skb is orphaned (not attached to a socket).
*/
if (!skb->sk || skb->destructor == sock_edemux)
skb->truesize += size - osize;
return 0;
nofrags:
kfree(data);
nodata:
return -ENOMEM;
}
EXPORT_SYMBOL(pskb_expand_head);
/* Make private copy of skb with writable head and some headroom */
struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
{
struct sk_buff *skb2;
int delta = headroom - skb_headroom(skb);
if (delta <= 0)
skb2 = pskb_copy(skb, GFP_ATOMIC);
else {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
GFP_ATOMIC)) {
kfree_skb(skb2);
skb2 = NULL;
}
}
return skb2;
}
EXPORT_SYMBOL(skb_realloc_headroom);
/**
* skb_copy_expand - copy and expand sk_buff
* @skb: buffer to copy
* @newheadroom: new free bytes at head
* @newtailroom: new free bytes at tail
* @gfp_mask: allocation priority
*
* Make a copy of both an &sk_buff and its data and while doing so
* allocate additional space.
*
* This is used when the caller wishes to modify the data and needs a
* private copy of the data to alter as well as more space for new fields.
* Returns %NULL on failure or the pointer to the buffer
* on success. The returned buffer has a reference count of 1.
*
* You must pass %GFP_ATOMIC as the allocation priority if this function
* is called from an interrupt.
*/
struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
int newheadroom, int newtailroom,
gfp_t gfp_mask)
{
/*
* Allocate the copy buffer
*/
struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
gfp_mask, skb_alloc_rx_flag(skb),
NUMA_NO_NODE);
int oldheadroom = skb_headroom(skb);
int head_copy_len, head_copy_off;
if (!n)
return NULL;
skb_reserve(n, newheadroom);
/* Set the tail pointer and length */
skb_put(n, skb->len);
head_copy_len = oldheadroom;
head_copy_off = 0;
if (newheadroom <= head_copy_len)
head_copy_len = newheadroom;
else
head_copy_off = newheadroom - head_copy_len;
/* Copy the linear header and data. */
if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
skb->len + head_copy_len))
BUG();
copy_skb_header(n, skb);
skb_headers_offset_update(n, newheadroom - oldheadroom);
return n;
}
EXPORT_SYMBOL(skb_copy_expand);
/**
* skb_pad - zero pad the tail of an skb
* @skb: buffer to pad
* @pad: space to pad
*
* Ensure that a buffer is followed by a padding area that is zero
* filled. Used by network drivers which may DMA or transfer data
* beyond the buffer end onto the wire.
*
* May return error in out of memory cases. The skb is freed on error.
*/
int skb_pad(struct sk_buff *skb, int pad)
{
int err;
int ntail;
/* If the skbuff is non linear tailroom is always zero.. */
if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
memset(skb->data+skb->len, 0, pad);
return 0;
}
ntail = skb->data_len + pad - (skb->end - skb->tail);
if (likely(skb_cloned(skb) || ntail > 0)) {
err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
if (unlikely(err))
goto free_skb;
}
/* FIXME: The use of this function with non-linear skb's really needs
* to be audited.
*/
err = skb_linearize(skb);
if (unlikely(err))
goto free_skb;
memset(skb->data + skb->len, 0, pad);
return 0;
free_skb:
kfree_skb(skb);
return err;
}
EXPORT_SYMBOL(skb_pad);
/**
* pskb_put - add data to the tail of a potentially fragmented buffer
* @skb: start of the buffer to use
* @tail: tail fragment of the buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the potentially
* fragmented buffer. @tail must be the last fragment of @skb -- or
* @skb itself. If this would exceed the total buffer size the kernel
* will panic. A pointer to the first byte of the extra data is
* returned.
*/
unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
{
if (tail != skb) {
skb->data_len += len;
skb->len += len;
}
return skb_put(tail, len);
}
EXPORT_SYMBOL_GPL(pskb_put);
/**
* skb_put - add data to a buffer
* @skb: buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the buffer. If this would
* exceed the total buffer size the kernel will panic. A pointer to the
* first byte of the extra data is returned.
*/
unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
{
unsigned char *tmp = skb_tail_pointer(skb);
SKB_LINEAR_ASSERT(skb);
skb->tail += len;
skb->len += len;
if (unlikely(skb->tail > skb->end))
skb_over_panic(skb, len, __builtin_return_address(0));
return tmp;
}
EXPORT_SYMBOL(skb_put);
/**
* skb_push - add data to the start of a buffer
* @skb: buffer to use
* @len: amount of data to add
*
* This function extends the used data area of the buffer at the buffer
* start. If this would exceed the total buffer headroom the kernel will
* panic. A pointer to the first byte of the extra data is returned.
*/
unsigned char *skb_push(struct sk_buff *skb, unsigned int len)
{
skb->data -= len;
skb->len += len;
if (unlikely(skb->data<skb->head))
skb_under_panic(skb, len, __builtin_return_address(0));
return skb->data;
}
EXPORT_SYMBOL(skb_push);
/**
* skb_pull - remove data from the start of a buffer
* @skb: buffer to use
* @len: amount of data to remove
*
* This function removes data from the start of a buffer, returning
* the memory to the headroom. A pointer to the next data in the buffer
* is returned. Once the data has been pulled future pushes will overwrite
* the old data.
*/
unsigned char *skb_pull(struct sk_buff *skb, unsigned int len)
{
return skb_pull_inline(skb, len);
}
EXPORT_SYMBOL(skb_pull);
/**
* skb_trim - remove end from a buffer
* @skb: buffer to alter
* @len: new length
*
* Cut the length of a buffer down by removing data from the tail. If
* the buffer is already under the length specified it is not modified.
* The skb must be linear.
*/
void skb_trim(struct sk_buff *skb, unsigned int len)
{
if (skb->len > len)
__skb_trim(skb, len);
}
EXPORT_SYMBOL(skb_trim);
/* Trims skb to length len. It can change skb pointers.
*/
int ___pskb_trim(struct sk_buff *skb, unsigned int len)
{
struct sk_buff **fragp;
struct sk_buff *frag;
int offset = skb_headlen(skb);
int nfrags = skb_shinfo(skb)->nr_frags;
int i;
int err;
if (skb_cloned(skb) &&
unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
return err;
i = 0;
if (offset >= len)
goto drop_pages;
for (; i < nfrags; i++) {
int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (end < len) {
offset = end;
continue;
}
skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
drop_pages:
skb_shinfo(skb)->nr_frags = i;
for (; i < nfrags; i++)
skb_frag_unref(skb, i);
if (skb_has_frag_list(skb))
skb_drop_fraglist(skb);
goto done;
}
for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
fragp = &frag->next) {
int end = offset + frag->len;
if (skb_shared(frag)) {
struct sk_buff *nfrag;
nfrag = skb_clone(frag, GFP_ATOMIC);
if (unlikely(!nfrag))
return -ENOMEM;
nfrag->next = frag->next;
consume_skb(frag);
frag = nfrag;
*fragp = frag;
}
if (end < len) {
offset = end;
continue;
}
if (end > len &&
unlikely((err = pskb_trim(frag, len - offset))))
return err;
if (frag->next)
skb_drop_list(&frag->next);
break;
}
done:
if (len > skb_headlen(skb)) {
skb->data_len -= skb->len - len;
skb->len = len;
} else {
skb->len = len;
skb->data_len = 0;
skb_set_tail_pointer(skb, len);
}
return 0;
}
EXPORT_SYMBOL(___pskb_trim);
/**
* __pskb_pull_tail - advance tail of skb header
* @skb: buffer to reallocate
* @delta: number of bytes to advance tail
*
* The function makes a sense only on a fragmented &sk_buff,
* it expands header moving its tail forward and copying necessary
* data from fragmented part.
*
* &sk_buff MUST have reference count of 1.
*
* Returns %NULL (and &sk_buff does not change) if pull failed
* or value of new tail of skb in the case of success.
*
* All the pointers pointing into skb header may change and must be
* reloaded after call to this function.
*/
/* Moves tail of skb head forward, copying data from fragmented part,
* when it is necessary.
* 1. It may fail due to malloc failure.
* 2. It may change skb pointers.
*
* It is pretty complicated. Luckily, it is called only in exceptional cases.
*/
unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta)
{
/* If skb has not enough free space at tail, get new one
* plus 128 bytes for future expansions. If we have enough
* room at tail, reallocate without expansion only if skb is cloned.
*/
int i, k, eat = (skb->tail + delta) - skb->end;
if (eat > 0 || skb_cloned(skb)) {
if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
GFP_ATOMIC))
return NULL;
}
if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta))
BUG();
/* Optimization: no fragments, no reasons to preestimate
* size of pulled pages. Superb.
*/
if (!skb_has_frag_list(skb))
goto pull_pages;
/* Estimate size of pulled pages. */
eat = delta;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (size >= eat)
goto pull_pages;
eat -= size;
}
/* If we need update frag list, we are in troubles.
* Certainly, it possible to add an offset to skb data,
* but taking into account that pulling is expected to
* be very rare operation, it is worth to fight against
* further bloating skb head and crucify ourselves here instead.
* Pure masohism, indeed. 8)8)
*/
if (eat) {
struct sk_buff *list = skb_shinfo(skb)->frag_list;
struct sk_buff *clone = NULL;
struct sk_buff *insp = NULL;
do {
BUG_ON(!list);
if (list->len <= eat) {
/* Eaten as whole. */
eat -= list->len;
list = list->next;
insp = list;
} else {
/* Eaten partially. */
if (skb_shared(list)) {
/* Sucks! We need to fork list. :-( */
clone = skb_clone(list, GFP_ATOMIC);
if (!clone)
return NULL;
insp = list->next;
list = clone;
} else {
/* This may be pulled without
* problems. */
insp = list;
}
if (!pskb_pull(list, eat)) {
kfree_skb(clone);
return NULL;
}
break;
}
} while (eat);
/* Free pulled out fragments. */
while ((list = skb_shinfo(skb)->frag_list) != insp) {
skb_shinfo(skb)->frag_list = list->next;
kfree_skb(list);
}
/* And insert new clone at head. */
if (clone) {
clone->next = list;
skb_shinfo(skb)->frag_list = clone;
}
}
/* Success! Now we may commit changes to skb data. */
pull_pages:
eat = delta;
k = 0;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (size <= eat) {
skb_frag_unref(skb, i);
eat -= size;
} else {
skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i];
if (eat) {
skb_shinfo(skb)->frags[k].page_offset += eat;
skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat);
eat = 0;
}
k++;
}
}
skb_shinfo(skb)->nr_frags = k;
skb->tail += delta;
skb->data_len -= delta;
return skb_tail_pointer(skb);
}
EXPORT_SYMBOL(__pskb_pull_tail);
/**
* skb_copy_bits - copy bits from skb to kernel buffer
* @skb: source skb
* @offset: offset in source
* @to: destination buffer
* @len: number of bytes to copy
*
* Copy the specified number of bytes from the source skb to the
* destination buffer.
*
* CAUTION ! :
* If its prototype is ever changed,
* check arch/{*}/net/{*}.S files,
* since it is called from BPF assembly code.
*/
int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
{
int start = skb_headlen(skb);
struct sk_buff *frag_iter;
int i, copy;
if (offset > (int)skb->len - len)
goto fault;
/* Copy header. */
if ((copy = start - offset) > 0) {
if (copy > len)
copy = len;
skb_copy_from_linear_data_offset(skb, offset, to, copy);
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
skb_frag_t *f = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(f);
if ((copy = end - offset) > 0) {
u8 *vaddr;
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(f));
memcpy(to,
vaddr + f->page_offset + offset - start,
copy);
kunmap_atomic(vaddr);
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_copy_bits(frag_iter, offset - start, to, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
to += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_copy_bits);
/*
* Callback from splice_to_pipe(), if we need to release some pages
* at the end of the spd in case we error'ed out in filling the pipe.
*/
static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
{
put_page(spd->pages[i]);
}
static struct page *linear_to_page(struct page *page, unsigned int *len,
unsigned int *offset,
struct sock *sk)
{
struct page_frag *pfrag = sk_page_frag(sk);
if (!sk_page_frag_refill(sk, pfrag))
return NULL;
*len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
memcpy(page_address(pfrag->page) + pfrag->offset,
page_address(page) + *offset, *len);
*offset = pfrag->offset;
pfrag->offset += *len;
return pfrag->page;
}
static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
struct page *page,
unsigned int offset)
{
return spd->nr_pages &&
spd->pages[spd->nr_pages - 1] == page &&
(spd->partial[spd->nr_pages - 1].offset +
spd->partial[spd->nr_pages - 1].len == offset);
}
/*
* Fill page/offset/length into spd, if it can hold more pages.
*/
static bool spd_fill_page(struct splice_pipe_desc *spd,
struct pipe_inode_info *pipe, struct page *page,
unsigned int *len, unsigned int offset,
bool linear,
struct sock *sk)
{
if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
return true;
if (linear) {
page = linear_to_page(page, len, &offset, sk);
if (!page)
return true;
}
if (spd_can_coalesce(spd, page, offset)) {
spd->partial[spd->nr_pages - 1].len += *len;
return false;
}
get_page(page);
spd->pages[spd->nr_pages] = page;
spd->partial[spd->nr_pages].len = *len;
spd->partial[spd->nr_pages].offset = offset;
spd->nr_pages++;
return false;
}
static bool __splice_segment(struct page *page, unsigned int poff,
unsigned int plen, unsigned int *off,
unsigned int *len,
struct splice_pipe_desc *spd, bool linear,
struct sock *sk,
struct pipe_inode_info *pipe)
{
if (!*len)
return true;
/* skip this segment if already processed */
if (*off >= plen) {
*off -= plen;
return false;
}
/* ignore any bits we already processed */
poff += *off;
plen -= *off;
*off = 0;
do {
unsigned int flen = min(*len, plen);
if (spd_fill_page(spd, pipe, page, &flen, poff,
linear, sk))
return true;
poff += flen;
plen -= flen;
*len -= flen;
} while (*len && plen);
return false;
}
/*
* Map linear and fragment data from the skb to spd. It reports true if the
* pipe is full or if we already spliced the requested length.
*/
static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
unsigned int *offset, unsigned int *len,
struct splice_pipe_desc *spd, struct sock *sk)
{
int seg;
struct sk_buff *iter;
/* map the linear part :
* If skb->head_frag is set, this 'linear' part is backed by a
* fragment, and if the head is not shared with any clones then
* we can avoid a copy since we own the head portion of this page.
*/
if (__splice_segment(virt_to_page(skb->data),
(unsigned long) skb->data & (PAGE_SIZE - 1),
skb_headlen(skb),
offset, len, spd,
skb_head_is_locked(skb),
sk, pipe))
return true;
/*
* then map the fragments
*/
for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
if (__splice_segment(skb_frag_page(f),
f->page_offset, skb_frag_size(f),
offset, len, spd, false, sk, pipe))
return true;
}
skb_walk_frags(skb, iter) {
if (*offset >= iter->len) {
*offset -= iter->len;
continue;
}
/* __skb_splice_bits() only fails if the output has no room
* left, so no point in going over the frag_list for the error
* case.
*/
if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
return true;
}
return false;
}
/*
* Map data from the skb to a pipe. Should handle both the linear part,
* the fragments, and the frag list.
*/
int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
struct pipe_inode_info *pipe, unsigned int tlen,
unsigned int flags)
{
struct partial_page partial[MAX_SKB_FRAGS];
struct page *pages[MAX_SKB_FRAGS];
struct splice_pipe_desc spd = {
.pages = pages,
.partial = partial,
.nr_pages_max = MAX_SKB_FRAGS,
.flags = flags,
.ops = &nosteal_pipe_buf_ops,
.spd_release = sock_spd_release,
};
int ret = 0;
__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
if (spd.nr_pages)
ret = splice_to_pipe(pipe, &spd);
return ret;
}
EXPORT_SYMBOL_GPL(skb_splice_bits);
/**
* skb_store_bits - store bits from kernel buffer to skb
* @skb: destination buffer
* @offset: offset in destination
* @from: source buffer
* @len: number of bytes to copy
*
* Copy the specified number of bytes from the source buffer to the
* destination skb. This function handles all the messy bits of
* traversing fragment lists and such.
*/
int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
{
int start = skb_headlen(skb);
struct sk_buff *frag_iter;
int i, copy;
if (offset > (int)skb->len - len)
goto fault;
if ((copy = start - offset) > 0) {
if (copy > len)
copy = len;
skb_copy_to_linear_data_offset(skb, offset, from, copy);
if ((len -= copy) == 0)
return 0;
offset += copy;
from += copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
int end;
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
u8 *vaddr;
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(frag));
memcpy(vaddr + frag->page_offset + offset - start,
from, copy);
kunmap_atomic(vaddr);
if ((len -= copy) == 0)
return 0;
offset += copy;
from += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
if (skb_store_bits(frag_iter, offset - start,
from, copy))
goto fault;
if ((len -= copy) == 0)
return 0;
offset += copy;
from += copy;
}
start = end;
}
if (!len)
return 0;
fault:
return -EFAULT;
}
EXPORT_SYMBOL(skb_store_bits);
/* Checksum skb data. */
__wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
__wsum csum, const struct skb_checksum_ops *ops)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int pos = 0;
/* Checksum header. */
if (copy > 0) {
if (copy > len)
copy = len;
csum = ops->update(skb->data + offset, copy, csum);
if ((len -= copy) == 0)
return csum;
offset += copy;
pos = copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
WARN_ON(start > offset + len);
end = start + skb_frag_size(frag);
if ((copy = end - offset) > 0) {
__wsum csum2;
u8 *vaddr;
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(frag));
csum2 = ops->update(vaddr + frag->page_offset +
offset - start, copy, 0);
kunmap_atomic(vaddr);
csum = ops->combine(csum, csum2, pos, copy);
if (!(len -= copy))
return csum;
offset += copy;
pos += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
__wsum csum2;
if (copy > len)
copy = len;
csum2 = __skb_checksum(frag_iter, offset - start,
copy, 0, ops);
csum = ops->combine(csum, csum2, pos, copy);
if ((len -= copy) == 0)
return csum;
offset += copy;
pos += copy;
}
start = end;
}
BUG_ON(len);
return csum;
}
EXPORT_SYMBOL(__skb_checksum);
__wsum skb_checksum(const struct sk_buff *skb, int offset,
int len, __wsum csum)
{
const struct skb_checksum_ops ops = {
.update = csum_partial_ext,
.combine = csum_block_add_ext,
};
return __skb_checksum(skb, offset, len, csum, &ops);
}
EXPORT_SYMBOL(skb_checksum);
/* Both of above in one bottle. */
__wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
u8 *to, int len, __wsum csum)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int pos = 0;
/* Copy header. */
if (copy > 0) {
if (copy > len)
copy = len;
csum = csum_partial_copy_nocheck(skb->data + offset, to,
copy, csum);
if ((len -= copy) == 0)
return csum;
offset += copy;
to += copy;
pos = copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
WARN_ON(start > offset + len);
end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
if ((copy = end - offset) > 0) {
__wsum csum2;
u8 *vaddr;
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (copy > len)
copy = len;
vaddr = kmap_atomic(skb_frag_page(frag));
csum2 = csum_partial_copy_nocheck(vaddr +
frag->page_offset +
offset - start, to,
copy, 0);
kunmap_atomic(vaddr);
csum = csum_block_add(csum, csum2, pos);
if (!(len -= copy))
return csum;
offset += copy;
to += copy;
pos += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
__wsum csum2;
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
csum2 = skb_copy_and_csum_bits(frag_iter,
offset - start,
to, copy, 0);
csum = csum_block_add(csum, csum2, pos);
if ((len -= copy) == 0)
return csum;
offset += copy;
to += copy;
pos += copy;
}
start = end;
}
BUG_ON(len);
return csum;
}
EXPORT_SYMBOL(skb_copy_and_csum_bits);
/**
* skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
* @from: source buffer
*
* Calculates the amount of linear headroom needed in the 'to' skb passed
* into skb_zerocopy().
*/
unsigned int
skb_zerocopy_headlen(const struct sk_buff *from)
{
unsigned int hlen = 0;
if (!from->head_frag ||
skb_headlen(from) < L1_CACHE_BYTES ||
skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
hlen = skb_headlen(from);
if (skb_has_frag_list(from))
hlen = from->len;
return hlen;
}
EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
/**
* skb_zerocopy - Zero copy skb to skb
* @to: destination buffer
* @from: source buffer
* @len: number of bytes to copy from source buffer
* @hlen: size of linear headroom in destination buffer
*
* Copies up to `len` bytes from `from` to `to` by creating references
* to the frags in the source buffer.
*
* The `hlen` as calculated by skb_zerocopy_headlen() specifies the
* headroom in the `to` buffer.
*
* Return value:
* 0: everything is OK
* -ENOMEM: couldn't orphan frags of @from due to lack of memory
* -EFAULT: skb_copy_bits() found some problem with skb geometry
*/
int
skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
{
int i, j = 0;
int plen = 0; /* length of skb->head fragment */
int ret;
struct page *page;
unsigned int offset;
BUG_ON(!from->head_frag && !hlen);
/* dont bother with small payloads */
if (len <= skb_tailroom(to))
return skb_copy_bits(from, 0, skb_put(to, len), len);
if (hlen) {
ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
if (unlikely(ret))
return ret;
len -= hlen;
} else {
plen = min_t(int, skb_headlen(from), len);
if (plen) {
page = virt_to_head_page(from->head);
offset = from->data - (unsigned char *)page_address(page);
__skb_fill_page_desc(to, 0, page, offset, plen);
get_page(page);
j = 1;
len -= plen;
}
}
to->truesize += len + plen;
to->len += len + plen;
to->data_len += len + plen;
if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
skb_tx_error(from);
return -ENOMEM;
}
for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
if (!len)
break;
skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
len -= skb_shinfo(to)->frags[j].size;
skb_frag_ref(to, j);
j++;
}
skb_shinfo(to)->nr_frags = j;
return 0;
}
EXPORT_SYMBOL_GPL(skb_zerocopy);
void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
{
__wsum csum;
long csstart;
if (skb->ip_summed == CHECKSUM_PARTIAL)
csstart = skb_checksum_start_offset(skb);
else
csstart = skb_headlen(skb);
BUG_ON(csstart > skb_headlen(skb));
skb_copy_from_linear_data(skb, to, csstart);
csum = 0;
if (csstart != skb->len)
csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
skb->len - csstart, 0);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
long csstuff = csstart + skb->csum_offset;
*((__sum16 *)(to + csstuff)) = csum_fold(csum);
}
}
EXPORT_SYMBOL(skb_copy_and_csum_dev);
/**
* skb_dequeue - remove from the head of the queue
* @list: list to dequeue from
*
* Remove the head of the list. The list lock is taken so the function
* may be used safely with other locking list functions. The head item is
* returned or %NULL if the list is empty.
*/
struct sk_buff *skb_dequeue(struct sk_buff_head *list)
{
unsigned long flags;
struct sk_buff *result;
spin_lock_irqsave(&list->lock, flags);
result = __skb_dequeue(list);
spin_unlock_irqrestore(&list->lock, flags);
return result;
}
EXPORT_SYMBOL(skb_dequeue);
/**
* skb_dequeue_tail - remove from the tail of the queue
* @list: list to dequeue from
*
* Remove the tail of the list. The list lock is taken so the function
* may be used safely with other locking list functions. The tail item is
* returned or %NULL if the list is empty.
*/
struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
{
unsigned long flags;
struct sk_buff *result;
spin_lock_irqsave(&list->lock, flags);
result = __skb_dequeue_tail(list);
spin_unlock_irqrestore(&list->lock, flags);
return result;
}
EXPORT_SYMBOL(skb_dequeue_tail);
/**
* skb_queue_purge - empty a list
* @list: list to empty
*
* Delete all buffers on an &sk_buff list. Each buffer is removed from
* the list and one reference dropped. This function takes the list
* lock and is atomic with respect to other list locking functions.
*/
void skb_queue_purge(struct sk_buff_head *list)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(list)) != NULL)
kfree_skb(skb);
}
EXPORT_SYMBOL(skb_queue_purge);
/**
* skb_rbtree_purge - empty a skb rbtree
* @root: root of the rbtree to empty
*
* Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
* the list and one reference dropped. This function does not take
* any lock. Synchronization should be handled by the caller (e.g., TCP
* out-of-order queue is protected by the socket lock).
*/
void skb_rbtree_purge(struct rb_root *root)
{
struct sk_buff *skb, *next;
rbtree_postorder_for_each_entry_safe(skb, next, root, rbnode)
kfree_skb(skb);
*root = RB_ROOT;
}
/**
* skb_queue_head - queue a buffer at the list head
* @list: list to use
* @newsk: buffer to queue
*
* Queue a buffer at the start of the list. This function takes the
* list lock and can be used safely with other locking &sk_buff functions
* safely.
*
* A buffer cannot be placed on two lists at the same time.
*/
void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_queue_head(list, newsk);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_queue_head);
/**
* skb_queue_tail - queue a buffer at the list tail
* @list: list to use
* @newsk: buffer to queue
*
* Queue a buffer at the tail of the list. This function takes the
* list lock and can be used safely with other locking &sk_buff functions
* safely.
*
* A buffer cannot be placed on two lists at the same time.
*/
void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_queue_tail(list, newsk);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_queue_tail);
/**
* skb_unlink - remove a buffer from a list
* @skb: buffer to remove
* @list: list to use
*
* Remove a packet from a list. The list locks are taken and this
* function is atomic with respect to other list locked calls
*
* You must know what list the SKB is on.
*/
void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_unlink(skb, list);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_unlink);
/**
* skb_append - append a buffer
* @old: buffer to insert after
* @newsk: buffer to insert
* @list: list to use
*
* Place a packet after a given packet in a list. The list locks are taken
* and this function is atomic with respect to other list locked calls.
* A buffer cannot be placed on two lists at the same time.
*/
void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_queue_after(list, old, newsk);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_append);
/**
* skb_insert - insert a buffer
* @old: buffer to insert before
* @newsk: buffer to insert
* @list: list to use
*
* Place a packet before a given packet in a list. The list locks are
* taken and this function is atomic with respect to other list locked
* calls.
*
* A buffer cannot be placed on two lists at the same time.
*/
void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
{
unsigned long flags;
spin_lock_irqsave(&list->lock, flags);
__skb_insert(newsk, old->prev, old, list);
spin_unlock_irqrestore(&list->lock, flags);
}
EXPORT_SYMBOL(skb_insert);
static inline void skb_split_inside_header(struct sk_buff *skb,
struct sk_buff* skb1,
const u32 len, const int pos)
{
int i;
skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
pos - len);
/* And move data appendix as is. */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
skb_shinfo(skb)->nr_frags = 0;
skb1->data_len = skb->data_len;
skb1->len += skb1->data_len;
skb->data_len = 0;
skb->len = len;
skb_set_tail_pointer(skb, len);
}
static inline void skb_split_no_header(struct sk_buff *skb,
struct sk_buff* skb1,
const u32 len, int pos)
{
int i, k = 0;
const int nfrags = skb_shinfo(skb)->nr_frags;
skb_shinfo(skb)->nr_frags = 0;
skb1->len = skb1->data_len = skb->len - len;
skb->len = len;
skb->data_len = len - pos;
for (i = 0; i < nfrags; i++) {
int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (pos + size > len) {
skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
if (pos < len) {
/* Split frag.
* We have two variants in this case:
* 1. Move all the frag to the second
* part, if it is possible. F.e.
* this approach is mandatory for TUX,
* where splitting is expensive.
* 2. Split is accurately. We make this.
*/
skb_frag_ref(skb, i);
skb_shinfo(skb1)->frags[0].page_offset += len - pos;
skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
skb_shinfo(skb)->nr_frags++;
}
k++;
} else
skb_shinfo(skb)->nr_frags++;
pos += size;
}
skb_shinfo(skb1)->nr_frags = k;
}
/**
* skb_split - Split fragmented skb to two parts at length len.
* @skb: the buffer to split
* @skb1: the buffer to receive the second part
* @len: new length for skb
*/
void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
{
int pos = skb_headlen(skb);
skb_shinfo(skb1)->tx_flags = skb_shinfo(skb)->tx_flags & SKBTX_SHARED_FRAG;
if (len < pos) /* Split line is inside header. */
skb_split_inside_header(skb, skb1, len, pos);
else /* Second chunk has no header, nothing to copy. */
skb_split_no_header(skb, skb1, len, pos);
}
EXPORT_SYMBOL(skb_split);
/* Shifting from/to a cloned skb is a no-go.
*
* Caller cannot keep skb_shinfo related pointers past calling here!
*/
static int skb_prepare_for_shift(struct sk_buff *skb)
{
return skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
}
/**
* skb_shift - Shifts paged data partially from skb to another
* @tgt: buffer into which tail data gets added
* @skb: buffer from which the paged data comes from
* @shiftlen: shift up to this many bytes
*
* Attempts to shift up to shiftlen worth of bytes, which may be less than
* the length of the skb, from skb to tgt. Returns number bytes shifted.
* It's up to caller to free skb if everything was shifted.
*
* If @tgt runs out of frags, the whole operation is aborted.
*
* Skb cannot include anything else but paged data while tgt is allowed
* to have non-paged data as well.
*
* TODO: full sized shift could be optimized but that would need
* specialized skb free'er to handle frags without up-to-date nr_frags.
*/
int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
{
int from, to, merge, todo;
struct skb_frag_struct *fragfrom, *fragto;
BUG_ON(shiftlen > skb->len);
if (skb_headlen(skb))
return 0;
todo = shiftlen;
from = 0;
to = skb_shinfo(tgt)->nr_frags;
fragfrom = &skb_shinfo(skb)->frags[from];
/* Actual merge is delayed until the point when we know we can
* commit all, so that we don't have to undo partial changes
*/
if (!to ||
!skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
fragfrom->page_offset)) {
merge = -1;
} else {
merge = to - 1;
todo -= skb_frag_size(fragfrom);
if (todo < 0) {
if (skb_prepare_for_shift(skb) ||
skb_prepare_for_shift(tgt))
return 0;
/* All previous frag pointers might be stale! */
fragfrom = &skb_shinfo(skb)->frags[from];
fragto = &skb_shinfo(tgt)->frags[merge];
skb_frag_size_add(fragto, shiftlen);
skb_frag_size_sub(fragfrom, shiftlen);
fragfrom->page_offset += shiftlen;
goto onlymerged;
}
from++;
}
/* Skip full, not-fitting skb to avoid expensive operations */
if ((shiftlen == skb->len) &&
(skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
return 0;
if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
return 0;
while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
if (to == MAX_SKB_FRAGS)
return 0;
fragfrom = &skb_shinfo(skb)->frags[from];
fragto = &skb_shinfo(tgt)->frags[to];
if (todo >= skb_frag_size(fragfrom)) {
*fragto = *fragfrom;
todo -= skb_frag_size(fragfrom);
from++;
to++;
} else {
__skb_frag_ref(fragfrom);
fragto->page = fragfrom->page;
fragto->page_offset = fragfrom->page_offset;
skb_frag_size_set(fragto, todo);
fragfrom->page_offset += todo;
skb_frag_size_sub(fragfrom, todo);
todo = 0;
to++;
break;
}
}
/* Ready to "commit" this state change to tgt */
skb_shinfo(tgt)->nr_frags = to;
if (merge >= 0) {
fragfrom = &skb_shinfo(skb)->frags[0];
fragto = &skb_shinfo(tgt)->frags[merge];
skb_frag_size_add(fragto, skb_frag_size(fragfrom));
__skb_frag_unref(fragfrom);
}
/* Reposition in the original skb */
to = 0;
while (from < skb_shinfo(skb)->nr_frags)
skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
skb_shinfo(skb)->nr_frags = to;
BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
onlymerged:
/* Most likely the tgt won't ever need its checksum anymore, skb on
* the other hand might need it if it needs to be resent
*/
tgt->ip_summed = CHECKSUM_PARTIAL;
skb->ip_summed = CHECKSUM_PARTIAL;
/* Yak, is it really working this way? Some helper please? */
skb->len -= shiftlen;
skb->data_len -= shiftlen;
skb->truesize -= shiftlen;
tgt->len += shiftlen;
tgt->data_len += shiftlen;
tgt->truesize += shiftlen;
return shiftlen;
}
/**
* skb_prepare_seq_read - Prepare a sequential read of skb data
* @skb: the buffer to read
* @from: lower offset of data to be read
* @to: upper offset of data to be read
* @st: state variable
*
* Initializes the specified state variable. Must be called before
* invoking skb_seq_read() for the first time.
*/
void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
unsigned int to, struct skb_seq_state *st)
{
st->lower_offset = from;
st->upper_offset = to;
st->root_skb = st->cur_skb = skb;
st->frag_idx = st->stepped_offset = 0;
st->frag_data = NULL;
}
EXPORT_SYMBOL(skb_prepare_seq_read);
/**
* skb_seq_read - Sequentially read skb data
* @consumed: number of bytes consumed by the caller so far
* @data: destination pointer for data to be returned
* @st: state variable
*
* Reads a block of skb data at @consumed relative to the
* lower offset specified to skb_prepare_seq_read(). Assigns
* the head of the data block to @data and returns the length
* of the block or 0 if the end of the skb data or the upper
* offset has been reached.
*
* The caller is not required to consume all of the data
* returned, i.e. @consumed is typically set to the number
* of bytes already consumed and the next call to
* skb_seq_read() will return the remaining part of the block.
*
* Note 1: The size of each block of data returned can be arbitrary,
* this limitation is the cost for zerocopy sequential
* reads of potentially non linear data.
*
* Note 2: Fragment lists within fragments are not implemented
* at the moment, state->root_skb could be replaced with
* a stack for this purpose.
*/
unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
struct skb_seq_state *st)
{
unsigned int block_limit, abs_offset = consumed + st->lower_offset;
skb_frag_t *frag;
if (unlikely(abs_offset >= st->upper_offset)) {
if (st->frag_data) {
kunmap_atomic(st->frag_data);
st->frag_data = NULL;
}
return 0;
}
next_skb:
block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
if (abs_offset < block_limit && !st->frag_data) {
*data = st->cur_skb->data + (abs_offset - st->stepped_offset);
return block_limit - abs_offset;
}
if (st->frag_idx == 0 && !st->frag_data)
st->stepped_offset += skb_headlen(st->cur_skb);
while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
block_limit = skb_frag_size(frag) + st->stepped_offset;
if (abs_offset < block_limit) {
if (!st->frag_data)
st->frag_data = kmap_atomic(skb_frag_page(frag));
*data = (u8 *) st->frag_data + frag->page_offset +
(abs_offset - st->stepped_offset);
return block_limit - abs_offset;
}
if (st->frag_data) {
kunmap_atomic(st->frag_data);
st->frag_data = NULL;
}
st->frag_idx++;
st->stepped_offset += skb_frag_size(frag);
}
if (st->frag_data) {
kunmap_atomic(st->frag_data);
st->frag_data = NULL;
}
if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
st->frag_idx = 0;
goto next_skb;
} else if (st->cur_skb->next) {
st->cur_skb = st->cur_skb->next;
st->frag_idx = 0;
goto next_skb;
}
return 0;
}
EXPORT_SYMBOL(skb_seq_read);
/**
* skb_abort_seq_read - Abort a sequential read of skb data
* @st: state variable
*
* Must be called if skb_seq_read() was not called until it
* returned 0.
*/
void skb_abort_seq_read(struct skb_seq_state *st)
{
if (st->frag_data)
kunmap_atomic(st->frag_data);
}
EXPORT_SYMBOL(skb_abort_seq_read);
#define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
struct ts_config *conf,
struct ts_state *state)
{
return skb_seq_read(offset, text, TS_SKB_CB(state));
}
static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
{
skb_abort_seq_read(TS_SKB_CB(state));
}
/**
* skb_find_text - Find a text pattern in skb data
* @skb: the buffer to look in
* @from: search offset
* @to: search limit
* @config: textsearch configuration
*
* Finds a pattern in the skb data according to the specified
* textsearch configuration. Use textsearch_next() to retrieve
* subsequent occurrences of the pattern. Returns the offset
* to the first occurrence or UINT_MAX if no match was found.
*/
unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
unsigned int to, struct ts_config *config)
{
struct ts_state state;
unsigned int ret;
config->get_next_block = skb_ts_get_next_block;
config->finish = skb_ts_finish;
skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
ret = textsearch_find(config, &state);
return (ret <= to - from ? ret : UINT_MAX);
}
EXPORT_SYMBOL(skb_find_text);
/**
* skb_append_datato_frags - append the user data to a skb
* @sk: sock structure
* @skb: skb structure to be appended with user data.
* @getfrag: call back function to be used for getting the user data
* @from: pointer to user message iov
* @length: length of the iov message
*
* Description: This procedure append the user data in the fragment part
* of the skb if any page alloc fails user this procedure returns -ENOMEM
*/
int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb,
int (*getfrag)(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length)
{
int frg_cnt = skb_shinfo(skb)->nr_frags;
int copy;
int offset = 0;
int ret;
struct page_frag *pfrag = ¤t->task_frag;
do {
/* Return error if we don't have space for new frag */
if (frg_cnt >= MAX_SKB_FRAGS)
return -EMSGSIZE;
if (!sk_page_frag_refill(sk, pfrag))
return -ENOMEM;
/* copy the user data to page */
copy = min_t(int, length, pfrag->size - pfrag->offset);
ret = getfrag(from, page_address(pfrag->page) + pfrag->offset,
offset, copy, 0, skb);
if (ret < 0)
return -EFAULT;
/* copy was successful so update the size parameters */
skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset,
copy);
frg_cnt++;
pfrag->offset += copy;
get_page(pfrag->page);
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
skb->len += copy;
skb->data_len += copy;
offset += copy;
length -= copy;
} while (length > 0);
return 0;
}
EXPORT_SYMBOL(skb_append_datato_frags);
int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
int offset, size_t size)
{
int i = skb_shinfo(skb)->nr_frags;
if (skb_can_coalesce(skb, i, page, offset)) {
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
} else if (i < MAX_SKB_FRAGS) {
get_page(page);
skb_fill_page_desc(skb, i, page, offset, size);
} else {
return -EMSGSIZE;
}
return 0;
}
EXPORT_SYMBOL_GPL(skb_append_pagefrags);
/**
* skb_pull_rcsum - pull skb and update receive checksum
* @skb: buffer to update
* @len: length of data pulled
*
* This function performs an skb_pull on the packet and updates
* the CHECKSUM_COMPLETE checksum. It should be used on
* receive path processing instead of skb_pull unless you know
* that the checksum difference is zero (e.g., a valid IP header)
* or you are setting ip_summed to CHECKSUM_NONE.
*/
unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
{
unsigned char *data = skb->data;
BUG_ON(len > skb->len);
__skb_pull(skb, len);
skb_postpull_rcsum(skb, data, len);
return skb->data;
}
EXPORT_SYMBOL_GPL(skb_pull_rcsum);
/**
* skb_segment - Perform protocol segmentation on skb.
* @head_skb: buffer to segment
* @features: features for the output path (see dev->features)
*
* This function performs segmentation on the given skb. It returns
* a pointer to the first in a list of new skbs for the segments.
* In case of error it returns ERR_PTR(err).
*/
struct sk_buff *skb_segment(struct sk_buff *head_skb,
netdev_features_t features)
{
struct sk_buff *segs = NULL;
struct sk_buff *tail = NULL;
struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
skb_frag_t *frag = skb_shinfo(head_skb)->frags;
unsigned int mss = skb_shinfo(head_skb)->gso_size;
unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
struct sk_buff *frag_skb = head_skb;
unsigned int offset = doffset;
unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
unsigned int partial_segs = 0;
unsigned int headroom;
unsigned int len = head_skb->len;
__be16 proto;
bool csum, sg;
int nfrags = skb_shinfo(head_skb)->nr_frags;
int err = -ENOMEM;
int i = 0;
int pos;
int dummy;
__skb_push(head_skb, doffset);
proto = skb_network_protocol(head_skb, &dummy);
if (unlikely(!proto))
return ERR_PTR(-EINVAL);
sg = !!(features & NETIF_F_SG);
csum = !!can_checksum_protocol(features, proto);
if (sg && csum && (mss != GSO_BY_FRAGS)) {
if (!(features & NETIF_F_GSO_PARTIAL)) {
struct sk_buff *iter;
if (!list_skb ||
!net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
goto normal;
/* Split the buffer at the frag_list pointer.
* This is based on the assumption that all
* buffers in the chain excluding the last
* containing the same amount of data.
*/
skb_walk_frags(head_skb, iter) {
if (skb_headlen(iter))
goto normal;
len -= iter->len;
}
}
/* GSO partial only requires that we trim off any excess that
* doesn't fit into an MSS sized block, so take care of that
* now.
*/
partial_segs = len / mss;
if (partial_segs > 1)
mss *= partial_segs;
else
partial_segs = 0;
}
normal:
headroom = skb_headroom(head_skb);
pos = skb_headlen(head_skb);
do {
struct sk_buff *nskb;
skb_frag_t *nskb_frag;
int hsize;
int size;
if (unlikely(mss == GSO_BY_FRAGS)) {
len = list_skb->len;
} else {
len = head_skb->len - offset;
if (len > mss)
len = mss;
}
hsize = skb_headlen(head_skb) - offset;
if (hsize < 0)
hsize = 0;
if (hsize > len || !sg)
hsize = len;
if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
(skb_headlen(list_skb) == len || sg)) {
BUG_ON(skb_headlen(list_skb) > len);
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
pos += skb_headlen(list_skb);
while (pos < offset + len) {
BUG_ON(i >= nfrags);
size = skb_frag_size(frag);
if (pos + size > offset + len)
break;
i++;
pos += size;
frag++;
}
nskb = skb_clone(list_skb, GFP_ATOMIC);
list_skb = list_skb->next;
if (unlikely(!nskb))
goto err;
if (unlikely(pskb_trim(nskb, len))) {
kfree_skb(nskb);
goto err;
}
hsize = skb_end_offset(nskb);
if (skb_cow_head(nskb, doffset + headroom)) {
kfree_skb(nskb);
goto err;
}
nskb->truesize += skb_end_offset(nskb) - hsize;
skb_release_head_state(nskb);
__skb_push(nskb, doffset);
} else {
nskb = __alloc_skb(hsize + doffset + headroom,
GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
NUMA_NO_NODE);
if (unlikely(!nskb))
goto err;
skb_reserve(nskb, headroom);
__skb_put(nskb, doffset);
}
if (segs)
tail->next = nskb;
else
segs = nskb;
tail = nskb;
__copy_skb_header(nskb, head_skb);
skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
skb_reset_mac_len(nskb);
skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
nskb->data - tnl_hlen,
doffset + tnl_hlen);
if (nskb->len == len + doffset)
goto perform_csum_check;
if (!sg) {
if (!nskb->remcsum_offload)
nskb->ip_summed = CHECKSUM_NONE;
SKB_GSO_CB(nskb)->csum =
skb_copy_and_csum_bits(head_skb, offset,
skb_put(nskb, len),
len, 0);
SKB_GSO_CB(nskb)->csum_start =
skb_headroom(nskb) + doffset;
continue;
}
nskb_frag = skb_shinfo(nskb)->frags;
skb_copy_from_linear_data_offset(head_skb, offset,
skb_put(nskb, hsize), hsize);
skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
SKBTX_SHARED_FRAG;
while (pos < offset + len) {
if (i >= nfrags) {
BUG_ON(skb_headlen(list_skb));
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
BUG_ON(!nfrags);
list_skb = list_skb->next;
}
if (unlikely(skb_shinfo(nskb)->nr_frags >=
MAX_SKB_FRAGS)) {
net_warn_ratelimited(
"skb_segment: too many frags: %u %u\n",
pos, mss);
goto err;
}
if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
goto err;
*nskb_frag = *frag;
__skb_frag_ref(nskb_frag);
size = skb_frag_size(nskb_frag);
if (pos < offset) {
nskb_frag->page_offset += offset - pos;
skb_frag_size_sub(nskb_frag, offset - pos);
}
skb_shinfo(nskb)->nr_frags++;
if (pos + size <= offset + len) {
i++;
frag++;
pos += size;
} else {
skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
goto skip_fraglist;
}
nskb_frag++;
}
skip_fraglist:
nskb->data_len = len - hsize;
nskb->len += nskb->data_len;
nskb->truesize += nskb->data_len;
perform_csum_check:
if (!csum) {
if (skb_has_shared_frag(nskb)) {
err = __skb_linearize(nskb);
if (err)
goto err;
}
if (!nskb->remcsum_offload)
nskb->ip_summed = CHECKSUM_NONE;
SKB_GSO_CB(nskb)->csum =
skb_checksum(nskb, doffset,
nskb->len - doffset, 0);
SKB_GSO_CB(nskb)->csum_start =
skb_headroom(nskb) + doffset;
}
} while ((offset += len) < head_skb->len);
/* Some callers want to get the end of the list.
* Put it in segs->prev to avoid walking the list.
* (see validate_xmit_skb_list() for example)
*/
segs->prev = tail;
if (partial_segs) {
struct sk_buff *iter;
int type = skb_shinfo(head_skb)->gso_type;
unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
/* Update type to add partial and then remove dodgy if set */
type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
type &= ~SKB_GSO_DODGY;
/* Update GSO info and prepare to start updating headers on
* our way back down the stack of protocols.
*/
for (iter = segs; iter; iter = iter->next) {
skb_shinfo(iter)->gso_size = gso_size;
skb_shinfo(iter)->gso_segs = partial_segs;
skb_shinfo(iter)->gso_type = type;
SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
}
if (tail->len - doffset <= gso_size)
skb_shinfo(tail)->gso_size = 0;
else if (tail != segs)
skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
}
/* Following permits correct backpressure, for protocols
* using skb_set_owner_w().
* Idea is to tranfert ownership from head_skb to last segment.
*/
if (head_skb->destructor == sock_wfree) {
swap(tail->truesize, head_skb->truesize);
swap(tail->destructor, head_skb->destructor);
swap(tail->sk, head_skb->sk);
}
return segs;
err:
kfree_skb_list(segs);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(skb_segment);
int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb)
{
struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
unsigned int offset = skb_gro_offset(skb);
unsigned int headlen = skb_headlen(skb);
unsigned int len = skb_gro_len(skb);
struct sk_buff *lp, *p = *head;
unsigned int delta_truesize;
if (unlikely(p->len + len >= 65536))
return -E2BIG;
lp = NAPI_GRO_CB(p)->last;
pinfo = skb_shinfo(lp);
if (headlen <= offset) {
skb_frag_t *frag;
skb_frag_t *frag2;
int i = skbinfo->nr_frags;
int nr_frags = pinfo->nr_frags + i;
if (nr_frags > MAX_SKB_FRAGS)
goto merge;
offset -= headlen;
pinfo->nr_frags = nr_frags;
skbinfo->nr_frags = 0;
frag = pinfo->frags + nr_frags;
frag2 = skbinfo->frags + i;
do {
*--frag = *--frag2;
} while (--i);
frag->page_offset += offset;
skb_frag_size_sub(frag, offset);
/* all fragments truesize : remove (head size + sk_buff) */
delta_truesize = skb->truesize -
SKB_TRUESIZE(skb_end_offset(skb));
skb->truesize -= skb->data_len;
skb->len -= skb->data_len;
skb->data_len = 0;
NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
goto done;
} else if (skb->head_frag) {
int nr_frags = pinfo->nr_frags;
skb_frag_t *frag = pinfo->frags + nr_frags;
struct page *page = virt_to_head_page(skb->head);
unsigned int first_size = headlen - offset;
unsigned int first_offset;
if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
goto merge;
first_offset = skb->data -
(unsigned char *)page_address(page) +
offset;
pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
frag->page.p = page;
frag->page_offset = first_offset;
skb_frag_size_set(frag, first_size);
memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
/* We dont need to clear skbinfo->nr_frags here */
delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
goto done;
}
merge:
delta_truesize = skb->truesize;
if (offset > headlen) {
unsigned int eat = offset - headlen;
skbinfo->frags[0].page_offset += eat;
skb_frag_size_sub(&skbinfo->frags[0], eat);
skb->data_len -= eat;
skb->len -= eat;
offset = headlen;
}
__skb_pull(skb, offset);
if (NAPI_GRO_CB(p)->last == p)
skb_shinfo(p)->frag_list = skb;
else
NAPI_GRO_CB(p)->last->next = skb;
NAPI_GRO_CB(p)->last = skb;
__skb_header_release(skb);
lp = p;
done:
NAPI_GRO_CB(p)->count++;
p->data_len += len;
p->truesize += delta_truesize;
p->len += len;
if (lp != p) {
lp->data_len += len;
lp->truesize += delta_truesize;
lp->len += len;
}
NAPI_GRO_CB(skb)->same_flow = 1;
return 0;
}
EXPORT_SYMBOL_GPL(skb_gro_receive);
void __init skb_init(void)
{
skbuff_head_cache = kmem_cache_create("skbuff_head_cache",
sizeof(struct sk_buff),
0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC,
NULL);
skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
sizeof(struct sk_buff_fclones),
0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC,
NULL);
}
/**
* skb_to_sgvec - Fill a scatter-gather list from a socket buffer
* @skb: Socket buffer containing the buffers to be mapped
* @sg: The scatter-gather list to map into
* @offset: The offset into the buffer's contents to start mapping
* @len: Length of buffer space to be mapped
*
* Fill the specified scatter-gather list with mappings/pointers into a
* region of the buffer space attached to a socket buffer.
*/
static int
__skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
int elt = 0;
if (copy > 0) {
if (copy > len)
copy = len;
sg_set_buf(sg, skb->data + offset, copy);
elt++;
if ((len -= copy) == 0)
return elt;
offset += copy;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
WARN_ON(start > offset + len);
end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
if ((copy = end - offset) > 0) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (copy > len)
copy = len;
sg_set_page(&sg[elt], skb_frag_page(frag), copy,
frag->page_offset+offset-start);
elt++;
if (!(len -= copy))
return elt;
offset += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
if ((copy = end - offset) > 0) {
if (copy > len)
copy = len;
elt += __skb_to_sgvec(frag_iter, sg+elt, offset - start,
copy);
if ((len -= copy) == 0)
return elt;
offset += copy;
}
start = end;
}
BUG_ON(len);
return elt;
}
/* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
* sglist without mark the sg which contain last skb data as the end.
* So the caller can mannipulate sg list as will when padding new data after
* the first call without calling sg_unmark_end to expend sg list.
*
* Scenario to use skb_to_sgvec_nomark:
* 1. sg_init_table
* 2. skb_to_sgvec_nomark(payload1)
* 3. skb_to_sgvec_nomark(payload2)
*
* This is equivalent to:
* 1. sg_init_table
* 2. skb_to_sgvec(payload1)
* 3. sg_unmark_end
* 4. skb_to_sgvec(payload2)
*
* When mapping mutilple payload conditionally, skb_to_sgvec_nomark
* is more preferable.
*/
int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
int offset, int len)
{
return __skb_to_sgvec(skb, sg, offset, len);
}
EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
{
int nsg = __skb_to_sgvec(skb, sg, offset, len);
sg_mark_end(&sg[nsg - 1]);
return nsg;
}
EXPORT_SYMBOL_GPL(skb_to_sgvec);
/**
* skb_cow_data - Check that a socket buffer's data buffers are writable
* @skb: The socket buffer to check.
* @tailbits: Amount of trailing space to be added
* @trailer: Returned pointer to the skb where the @tailbits space begins
*
* Make sure that the data buffers attached to a socket buffer are
* writable. If they are not, private copies are made of the data buffers
* and the socket buffer is set to use these instead.
*
* If @tailbits is given, make sure that there is space to write @tailbits
* bytes of data beyond current end of socket buffer. @trailer will be
* set to point to the skb in which this space begins.
*
* The number of scatterlist elements required to completely map the
* COW'd and extended socket buffer will be returned.
*/
int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
{
int copyflag;
int elt;
struct sk_buff *skb1, **skb_p;
/* If skb is cloned or its head is paged, reallocate
* head pulling out all the pages (pages are considered not writable
* at the moment even if they are anonymous).
*/
if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
__pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL)
return -ENOMEM;
/* Easy case. Most of packets will go this way. */
if (!skb_has_frag_list(skb)) {
/* A little of trouble, not enough of space for trailer.
* This should not happen, when stack is tuned to generate
* good frames. OK, on miss we reallocate and reserve even more
* space, 128 bytes is fair. */
if (skb_tailroom(skb) < tailbits &&
pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
return -ENOMEM;
/* Voila! */
*trailer = skb;
return 1;
}
/* Misery. We are in troubles, going to mincer fragments... */
elt = 1;
skb_p = &skb_shinfo(skb)->frag_list;
copyflag = 0;
while ((skb1 = *skb_p) != NULL) {
int ntail = 0;
/* The fragment is partially pulled by someone,
* this can happen on input. Copy it and everything
* after it. */
if (skb_shared(skb1))
copyflag = 1;
/* If the skb is the last, worry about trailer. */
if (skb1->next == NULL && tailbits) {
if (skb_shinfo(skb1)->nr_frags ||
skb_has_frag_list(skb1) ||
skb_tailroom(skb1) < tailbits)
ntail = tailbits + 128;
}
if (copyflag ||
skb_cloned(skb1) ||
ntail ||
skb_shinfo(skb1)->nr_frags ||
skb_has_frag_list(skb1)) {
struct sk_buff *skb2;
/* Fuck, we are miserable poor guys... */
if (ntail == 0)
skb2 = skb_copy(skb1, GFP_ATOMIC);
else
skb2 = skb_copy_expand(skb1,
skb_headroom(skb1),
ntail,
GFP_ATOMIC);
if (unlikely(skb2 == NULL))
return -ENOMEM;
if (skb1->sk)
skb_set_owner_w(skb2, skb1->sk);
/* Looking around. Are we still alive?
* OK, link new skb, drop old one */
skb2->next = skb1->next;
*skb_p = skb2;
kfree_skb(skb1);
skb1 = skb2;
}
elt++;
*trailer = skb1;
skb_p = &skb1->next;
}
return elt;
}
EXPORT_SYMBOL_GPL(skb_cow_data);
static void sock_rmem_free(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
}
static void skb_set_err_queue(struct sk_buff *skb)
{
/* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
* So, it is safe to (mis)use it to mark skbs on the error queue.
*/
skb->pkt_type = PACKET_OUTGOING;
BUILD_BUG_ON(PACKET_OUTGOING == 0);
}
/*
* Note: We dont mem charge error packets (no sk_forward_alloc changes)
*/
int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
{
if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
(unsigned int)sk->sk_rcvbuf)
return -ENOMEM;
skb_orphan(skb);
skb->sk = sk;
skb->destructor = sock_rmem_free;
atomic_add(skb->truesize, &sk->sk_rmem_alloc);
skb_set_err_queue(skb);
/* before exiting rcu section, make sure dst is refcounted */
skb_dst_force(skb);
skb_queue_tail(&sk->sk_error_queue, skb);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk);
return 0;
}
EXPORT_SYMBOL(sock_queue_err_skb);
static bool is_icmp_err_skb(const struct sk_buff *skb)
{
return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
}
struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
{
struct sk_buff_head *q = &sk->sk_error_queue;
struct sk_buff *skb, *skb_next = NULL;
bool icmp_next = false;
unsigned long flags;
spin_lock_irqsave(&q->lock, flags);
skb = __skb_dequeue(q);
if (skb && (skb_next = skb_peek(q)))
icmp_next = is_icmp_err_skb(skb_next);
spin_unlock_irqrestore(&q->lock, flags);
if (is_icmp_err_skb(skb) && !icmp_next)
sk->sk_err = 0;
if (skb_next)
sk->sk_error_report(sk);
return skb;
}
EXPORT_SYMBOL(sock_dequeue_err_skb);
/**
* skb_clone_sk - create clone of skb, and take reference to socket
* @skb: the skb to clone
*
* This function creates a clone of a buffer that holds a reference on
* sk_refcnt. Buffers created via this function are meant to be
* returned using sock_queue_err_skb, or free via kfree_skb.
*
* When passing buffers allocated with this function to sock_queue_err_skb
* it is necessary to wrap the call with sock_hold/sock_put in order to
* prevent the socket from being released prior to being enqueued on
* the sk_error_queue.
*/
struct sk_buff *skb_clone_sk(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct sk_buff *clone;
if (!sk || !atomic_inc_not_zero(&sk->sk_refcnt))
return NULL;
clone = skb_clone(skb, GFP_ATOMIC);
if (!clone) {
sock_put(sk);
return NULL;
}
clone->sk = sk;
clone->destructor = sock_efree;
return clone;
}
EXPORT_SYMBOL(skb_clone_sk);
static void __skb_complete_tx_timestamp(struct sk_buff *skb,
struct sock *sk,
int tstype,
bool opt_stats)
{
struct sock_exterr_skb *serr;
int err;
BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
serr = SKB_EXT_ERR(skb);
memset(serr, 0, sizeof(*serr));
serr->ee.ee_errno = ENOMSG;
serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
serr->ee.ee_info = tstype;
serr->opt_stats = opt_stats;
if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
serr->ee.ee_data = skb_shinfo(skb)->tskey;
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
serr->ee.ee_data -= sk->sk_tskey;
}
err = sock_queue_err_skb(sk, skb);
if (err)
kfree_skb(skb);
}
static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
{
bool ret;
if (likely(sysctl_tstamp_allow_data || tsonly))
return true;
read_lock_bh(&sk->sk_callback_lock);
ret = sk->sk_socket && sk->sk_socket->file &&
file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
read_unlock_bh(&sk->sk_callback_lock);
return ret;
}
void skb_complete_tx_timestamp(struct sk_buff *skb,
struct skb_shared_hwtstamps *hwtstamps)
{
struct sock *sk = skb->sk;
if (!skb_may_tx_timestamp(sk, false))
return;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
*skb_hwtstamps(skb) = *hwtstamps;
__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
sock_put(sk);
}
}
EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
void __skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps,
struct sock *sk, int tstype)
{
struct sk_buff *skb;
bool tsonly, opt_stats = false;
if (!sk)
return;
tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
if (!skb_may_tx_timestamp(sk, tsonly))
return;
if (tsonly) {
#ifdef CONFIG_INET
if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM) {
skb = tcp_get_timestamping_opt_stats(sk);
opt_stats = true;
} else
#endif
skb = alloc_skb(0, GFP_ATOMIC);
} else {
skb = skb_clone(orig_skb, GFP_ATOMIC);
}
if (!skb)
return;
if (tsonly) {
skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags;
skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
}
if (hwtstamps)
*skb_hwtstamps(skb) = *hwtstamps;
else
skb->tstamp = ktime_get_real();
__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
}
EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
void skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps)
{
return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk,
SCM_TSTAMP_SND);
}
EXPORT_SYMBOL_GPL(skb_tstamp_tx);
void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
{
struct sock *sk = skb->sk;
struct sock_exterr_skb *serr;
int err = 1;
skb->wifi_acked_valid = 1;
skb->wifi_acked = acked;
serr = SKB_EXT_ERR(skb);
memset(serr, 0, sizeof(*serr));
serr->ee.ee_errno = ENOMSG;
serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
/* Take a reference to prevent skb_orphan() from freeing the socket,
* but only if the socket refcount is not zero.
*/
if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
err = sock_queue_err_skb(sk, skb);
sock_put(sk);
}
if (err)
kfree_skb(skb);
}
EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
/**
* skb_partial_csum_set - set up and verify partial csum values for packet
* @skb: the skb to set
* @start: the number of bytes after skb->data to start checksumming.
* @off: the offset from start to place the checksum.
*
* For untrusted partially-checksummed packets, we need to make sure the values
* for skb->csum_start and skb->csum_offset are valid so we don't oops.
*
* This function checks and sets those values and skb->ip_summed: if this
* returns false you should drop the packet.
*/
bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
{
if (unlikely(start > skb_headlen(skb)) ||
unlikely((int)start + off > skb_headlen(skb) - 2)) {
net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n",
start, off, skb_headlen(skb));
return false;
}
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum_start = skb_headroom(skb) + start;
skb->csum_offset = off;
skb_set_transport_header(skb, start);
return true;
}
EXPORT_SYMBOL_GPL(skb_partial_csum_set);
static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
unsigned int max)
{
if (skb_headlen(skb) >= len)
return 0;
/* If we need to pullup then pullup to the max, so we
* won't need to do it again.
*/
if (max > skb->len)
max = skb->len;
if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
return -ENOMEM;
if (skb_headlen(skb) < len)
return -EPROTO;
return 0;
}
#define MAX_TCP_HDR_LEN (15 * 4)
static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
typeof(IPPROTO_IP) proto,
unsigned int off)
{
switch (proto) {
int err;
case IPPROTO_TCP:
err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
off + MAX_TCP_HDR_LEN);
if (!err && !skb_partial_csum_set(skb, off,
offsetof(struct tcphdr,
check)))
err = -EPROTO;
return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
case IPPROTO_UDP:
err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
off + sizeof(struct udphdr));
if (!err && !skb_partial_csum_set(skb, off,
offsetof(struct udphdr,
check)))
err = -EPROTO;
return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
}
return ERR_PTR(-EPROTO);
}
/* This value should be large enough to cover a tagged ethernet header plus
* maximally sized IP and TCP or UDP headers.
*/
#define MAX_IP_HDR_LEN 128
static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
{
unsigned int off;
bool fragment;
__sum16 *csum;
int err;
fragment = false;
err = skb_maybe_pull_tail(skb,
sizeof(struct iphdr),
MAX_IP_HDR_LEN);
if (err < 0)
goto out;
if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF))
fragment = true;
off = ip_hdrlen(skb);
err = -EPROTO;
if (fragment)
goto out;
csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
if (IS_ERR(csum))
return PTR_ERR(csum);
if (recalculate)
*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr,
skb->len - off,
ip_hdr(skb)->protocol, 0);
err = 0;
out:
return err;
}
/* This value should be large enough to cover a tagged ethernet header plus
* an IPv6 header, all options, and a maximal TCP or UDP header.
*/
#define MAX_IPV6_HDR_LEN 256
#define OPT_HDR(type, skb, off) \
(type *)(skb_network_header(skb) + (off))
static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
{
int err;
u8 nexthdr;
unsigned int off;
unsigned int len;
bool fragment;
bool done;
__sum16 *csum;
fragment = false;
done = false;
off = sizeof(struct ipv6hdr);
err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
nexthdr = ipv6_hdr(skb)->nexthdr;
len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
while (off <= len && !done) {
switch (nexthdr) {
case IPPROTO_DSTOPTS:
case IPPROTO_HOPOPTS:
case IPPROTO_ROUTING: {
struct ipv6_opt_hdr *hp;
err = skb_maybe_pull_tail(skb,
off +
sizeof(struct ipv6_opt_hdr),
MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
nexthdr = hp->nexthdr;
off += ipv6_optlen(hp);
break;
}
case IPPROTO_AH: {
struct ip_auth_hdr *hp;
err = skb_maybe_pull_tail(skb,
off +
sizeof(struct ip_auth_hdr),
MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
hp = OPT_HDR(struct ip_auth_hdr, skb, off);
nexthdr = hp->nexthdr;
off += ipv6_authlen(hp);
break;
}
case IPPROTO_FRAGMENT: {
struct frag_hdr *hp;
err = skb_maybe_pull_tail(skb,
off +
sizeof(struct frag_hdr),
MAX_IPV6_HDR_LEN);
if (err < 0)
goto out;
hp = OPT_HDR(struct frag_hdr, skb, off);
if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
fragment = true;
nexthdr = hp->nexthdr;
off += sizeof(struct frag_hdr);
break;
}
default:
done = true;
break;
}
}
err = -EPROTO;
if (!done || fragment)
goto out;
csum = skb_checksum_setup_ip(skb, nexthdr, off);
if (IS_ERR(csum))
return PTR_ERR(csum);
if (recalculate)
*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len - off, nexthdr, 0);
err = 0;
out:
return err;
}
/**
* skb_checksum_setup - set up partial checksum offset
* @skb: the skb to set up
* @recalculate: if true the pseudo-header checksum will be recalculated
*/
int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
{
int err;
switch (skb->protocol) {
case htons(ETH_P_IP):
err = skb_checksum_setup_ipv4(skb, recalculate);
break;
case htons(ETH_P_IPV6):
err = skb_checksum_setup_ipv6(skb, recalculate);
break;
default:
err = -EPROTO;
break;
}
return err;
}
EXPORT_SYMBOL(skb_checksum_setup);
/**
* skb_checksum_maybe_trim - maybe trims the given skb
* @skb: the skb to check
* @transport_len: the data length beyond the network header
*
* Checks whether the given skb has data beyond the given transport length.
* If so, returns a cloned skb trimmed to this transport length.
* Otherwise returns the provided skb. Returns NULL in error cases
* (e.g. transport_len exceeds skb length or out-of-memory).
*
* Caller needs to set the skb transport header and free any returned skb if it
* differs from the provided skb.
*/
static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
unsigned int transport_len)
{
struct sk_buff *skb_chk;
unsigned int len = skb_transport_offset(skb) + transport_len;
int ret;
if (skb->len < len)
return NULL;
else if (skb->len == len)
return skb;
skb_chk = skb_clone(skb, GFP_ATOMIC);
if (!skb_chk)
return NULL;
ret = pskb_trim_rcsum(skb_chk, len);
if (ret) {
kfree_skb(skb_chk);
return NULL;
}
return skb_chk;
}
/**
* skb_checksum_trimmed - validate checksum of an skb
* @skb: the skb to check
* @transport_len: the data length beyond the network header
* @skb_chkf: checksum function to use
*
* Applies the given checksum function skb_chkf to the provided skb.
* Returns a checked and maybe trimmed skb. Returns NULL on error.
*
* If the skb has data beyond the given transport length, then a
* trimmed & cloned skb is checked and returned.
*
* Caller needs to set the skb transport header and free any returned skb if it
* differs from the provided skb.
*/
struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
unsigned int transport_len,
__sum16(*skb_chkf)(struct sk_buff *skb))
{
struct sk_buff *skb_chk;
unsigned int offset = skb_transport_offset(skb);
__sum16 ret;
skb_chk = skb_checksum_maybe_trim(skb, transport_len);
if (!skb_chk)
goto err;
if (!pskb_may_pull(skb_chk, offset))
goto err;
skb_pull_rcsum(skb_chk, offset);
ret = skb_chkf(skb_chk);
skb_push_rcsum(skb_chk, offset);
if (ret)
goto err;
return skb_chk;
err:
if (skb_chk && skb_chk != skb)
kfree_skb(skb_chk);
return NULL;
}
EXPORT_SYMBOL(skb_checksum_trimmed);
void __skb_warn_lro_forwarding(const struct sk_buff *skb)
{
net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
skb->dev->name);
}
EXPORT_SYMBOL(__skb_warn_lro_forwarding);
void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
{
if (head_stolen) {
skb_release_head_state(skb);
kmem_cache_free(skbuff_head_cache, skb);
} else {
__kfree_skb(skb);
}
}
EXPORT_SYMBOL(kfree_skb_partial);
/**
* skb_try_coalesce - try to merge skb to prior one
* @to: prior buffer
* @from: buffer to add
* @fragstolen: pointer to boolean
* @delta_truesize: how much more was allocated than was requested
*/
bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
bool *fragstolen, int *delta_truesize)
{
int i, delta, len = from->len;
*fragstolen = false;
if (skb_cloned(to))
return false;
if (len <= skb_tailroom(to)) {
if (len)
BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
*delta_truesize = 0;
return true;
}
if (skb_has_frag_list(to) || skb_has_frag_list(from))
return false;
if (skb_headlen(from) != 0) {
struct page *page;
unsigned int offset;
if (skb_shinfo(to)->nr_frags +
skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
return false;
if (skb_head_is_locked(from))
return false;
delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
page = virt_to_head_page(from->head);
offset = from->data - (unsigned char *)page_address(page);
skb_fill_page_desc(to, skb_shinfo(to)->nr_frags,
page, offset, skb_headlen(from));
*fragstolen = true;
} else {
if (skb_shinfo(to)->nr_frags +
skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS)
return false;
delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
}
WARN_ON_ONCE(delta < len);
memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags,
skb_shinfo(from)->frags,
skb_shinfo(from)->nr_frags * sizeof(skb_frag_t));
skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags;
if (!skb_cloned(from))
skb_shinfo(from)->nr_frags = 0;
/* if the skb is not cloned this does nothing
* since we set nr_frags to 0.
*/
for (i = 0; i < skb_shinfo(from)->nr_frags; i++)
skb_frag_ref(from, i);
to->truesize += delta;
to->len += len;
to->data_len += len;
*delta_truesize = delta;
return true;
}
EXPORT_SYMBOL(skb_try_coalesce);
/**
* skb_scrub_packet - scrub an skb
*
* @skb: buffer to clean
* @xnet: packet is crossing netns
*
* skb_scrub_packet can be used after encapsulating or decapsulting a packet
* into/from a tunnel. Some information have to be cleared during these
* operations.
* skb_scrub_packet can also be used to clean a skb before injecting it in
* another namespace (@xnet == true). We have to clear all information in the
* skb that could impact namespace isolation.
*/
void skb_scrub_packet(struct sk_buff *skb, bool xnet)
{
skb->tstamp = 0;
skb->pkt_type = PACKET_HOST;
skb->skb_iif = 0;
skb->ignore_df = 0;
skb_dst_drop(skb);
secpath_reset(skb);
nf_reset(skb);
nf_reset_trace(skb);
if (!xnet)
return;
skb_orphan(skb);
skb->mark = 0;
}
EXPORT_SYMBOL_GPL(skb_scrub_packet);
/**
* skb_gso_transport_seglen - Return length of individual segments of a gso packet
*
* @skb: GSO skb
*
* skb_gso_transport_seglen is used to determine the real size of the
* individual segments, including Layer4 headers (TCP/UDP).
*
* The MAC/L2 or network (IP, IPv6) headers are not accounted for.
*/
unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
unsigned int thlen = 0;
if (skb->encapsulation) {
thlen = skb_inner_transport_header(skb) -
skb_transport_header(skb);
if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
thlen += inner_tcp_hdrlen(skb);
} else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
thlen = tcp_hdrlen(skb);
} else if (unlikely(shinfo->gso_type & SKB_GSO_SCTP)) {
thlen = sizeof(struct sctphdr);
}
/* UFO sets gso_size to the size of the fragmentation
* payload, i.e. the size of the L4 (UDP) header is already
* accounted for.
*/
return thlen + shinfo->gso_size;
}
EXPORT_SYMBOL_GPL(skb_gso_transport_seglen);
/**
* skb_gso_validate_mtu - Return in case such skb fits a given MTU
*
* @skb: GSO skb
* @mtu: MTU to validate against
*
* skb_gso_validate_mtu validates if a given skb will fit a wanted MTU
* once split.
*/
bool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu)
{
const struct skb_shared_info *shinfo = skb_shinfo(skb);
const struct sk_buff *iter;
unsigned int hlen;
hlen = skb_gso_network_seglen(skb);
if (shinfo->gso_size != GSO_BY_FRAGS)
return hlen <= mtu;
/* Undo this so we can re-use header sizes */
hlen -= GSO_BY_FRAGS;
skb_walk_frags(skb, iter) {
if (hlen + skb_headlen(iter) > mtu)
return false;
}
return true;
}
EXPORT_SYMBOL_GPL(skb_gso_validate_mtu);
static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
{
if (skb_cow(skb, skb_headroom(skb)) < 0) {
kfree_skb(skb);
return NULL;
}
memmove(skb->data - ETH_HLEN, skb->data - skb->mac_len - VLAN_HLEN,
2 * ETH_ALEN);
skb->mac_header += VLAN_HLEN;
return skb;
}
struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
{
struct vlan_hdr *vhdr;
u16 vlan_tci;
if (unlikely(skb_vlan_tag_present(skb))) {
/* vlan_tci is already set-up so leave this for another time */
return skb;
}
skb = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(!skb))
goto err_free;
if (unlikely(!pskb_may_pull(skb, VLAN_HLEN)))
goto err_free;
vhdr = (struct vlan_hdr *)skb->data;
vlan_tci = ntohs(vhdr->h_vlan_TCI);
__vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
skb_pull_rcsum(skb, VLAN_HLEN);
vlan_set_encap_proto(skb, vhdr);
skb = skb_reorder_vlan_header(skb);
if (unlikely(!skb))
goto err_free;
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb_reset_mac_len(skb);
return skb;
err_free:
kfree_skb(skb);
return NULL;
}
EXPORT_SYMBOL(skb_vlan_untag);
int skb_ensure_writable(struct sk_buff *skb, int write_len)
{
if (!pskb_may_pull(skb, write_len))
return -ENOMEM;
if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
return 0;
return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
}
EXPORT_SYMBOL(skb_ensure_writable);
/* remove VLAN header from packet and update csum accordingly.
* expects a non skb_vlan_tag_present skb with a vlan tag payload
*/
int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
{
struct vlan_hdr *vhdr;
int offset = skb->data - skb_mac_header(skb);
int err;
if (WARN_ONCE(offset,
"__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
offset)) {
return -EINVAL;
}
err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
if (unlikely(err))
return err;
skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
*vlan_tci = ntohs(vhdr->h_vlan_TCI);
memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
__skb_pull(skb, VLAN_HLEN);
vlan_set_encap_proto(skb, vhdr);
skb->mac_header += VLAN_HLEN;
if (skb_network_offset(skb) < ETH_HLEN)
skb_set_network_header(skb, ETH_HLEN);
skb_reset_mac_len(skb);
return err;
}
EXPORT_SYMBOL(__skb_vlan_pop);
/* Pop a vlan tag either from hwaccel or from payload.
* Expects skb->data at mac header.
*/
int skb_vlan_pop(struct sk_buff *skb)
{
u16 vlan_tci;
__be16 vlan_proto;
int err;
if (likely(skb_vlan_tag_present(skb))) {
skb->vlan_tci = 0;
} else {
if (unlikely(!eth_type_vlan(skb->protocol)))
return 0;
err = __skb_vlan_pop(skb, &vlan_tci);
if (err)
return err;
}
/* move next vlan tag to hw accel tag */
if (likely(!eth_type_vlan(skb->protocol)))
return 0;
vlan_proto = skb->protocol;
err = __skb_vlan_pop(skb, &vlan_tci);
if (unlikely(err))
return err;
__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
return 0;
}
EXPORT_SYMBOL(skb_vlan_pop);
/* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
* Expects skb->data at mac header.
*/
int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
{
if (skb_vlan_tag_present(skb)) {
int offset = skb->data - skb_mac_header(skb);
int err;
if (WARN_ONCE(offset,
"skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
offset)) {
return -EINVAL;
}
err = __vlan_insert_tag(skb, skb->vlan_proto,
skb_vlan_tag_get(skb));
if (err)
return err;
skb->protocol = skb->vlan_proto;
skb->mac_len += VLAN_HLEN;
skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
}
__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
return 0;
}
EXPORT_SYMBOL(skb_vlan_push);
/**
* alloc_skb_with_frags - allocate skb with page frags
*
* @header_len: size of linear part
* @data_len: needed length in frags
* @max_page_order: max page order desired.
* @errcode: pointer to error code if any
* @gfp_mask: allocation mask
*
* This can be used to allocate a paged skb, given a maximal order for frags.
*/
struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
unsigned long data_len,
int max_page_order,
int *errcode,
gfp_t gfp_mask)
{
int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
unsigned long chunk;
struct sk_buff *skb;
struct page *page;
gfp_t gfp_head;
int i;
*errcode = -EMSGSIZE;
/* Note this test could be relaxed, if we succeed to allocate
* high order pages...
*/
if (npages > MAX_SKB_FRAGS)
return NULL;
gfp_head = gfp_mask;
if (gfp_head & __GFP_DIRECT_RECLAIM)
gfp_head |= __GFP_REPEAT;
*errcode = -ENOBUFS;
skb = alloc_skb(header_len, gfp_head);
if (!skb)
return NULL;
skb->truesize += npages << PAGE_SHIFT;
for (i = 0; npages > 0; i++) {
int order = max_page_order;
while (order) {
if (npages >= 1 << order) {
page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
__GFP_COMP |
__GFP_NOWARN |
__GFP_NORETRY,
order);
if (page)
goto fill_page;
/* Do not retry other high order allocations */
order = 1;
max_page_order = 0;
}
order--;
}
page = alloc_page(gfp_mask);
if (!page)
goto failure;
fill_page:
chunk = min_t(unsigned long, data_len,
PAGE_SIZE << order);
skb_fill_page_desc(skb, i, page, 0, chunk);
data_len -= chunk;
npages -= 1 << order;
}
return skb;
failure:
kfree_skb(skb);
return NULL;
}
EXPORT_SYMBOL(alloc_skb_with_frags);
/* carve out the first off bytes from skb when off < headlen */
static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
const int headlen, gfp_t gfp_mask)
{
int i;
int size = skb_end_offset(skb);
int new_hlen = headlen - off;
u8 *data;
size = SKB_DATA_ALIGN(size);
if (skb_pfmemalloc(skb))
gfp_mask |= __GFP_MEMALLOC;
data = kmalloc_reserve(size +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
gfp_mask, NUMA_NO_NODE, NULL);
if (!data)
return -ENOMEM;
size = SKB_WITH_OVERHEAD(ksize(data));
/* Copy real data, and all frags */
skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
skb->len -= off;
memcpy((struct skb_shared_info *)(data + size),
skb_shinfo(skb),
offsetof(struct skb_shared_info,
frags[skb_shinfo(skb)->nr_frags]));
if (skb_cloned(skb)) {
/* drop the old head gracefully */
if (skb_orphan_frags(skb, gfp_mask)) {
kfree(data);
return -ENOMEM;
}
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_frag_ref(skb, i);
if (skb_has_frag_list(skb))
skb_clone_fraglist(skb);
skb_release_data(skb);
} else {
/* we can reuse existing recount- all we did was
* relocate values
*/
skb_free_head(skb);
}
skb->head = data;
skb->data = data;
skb->head_frag = 0;
#ifdef NET_SKBUFF_DATA_USES_OFFSET
skb->end = size;
#else
skb->end = skb->head + size;
#endif
skb_set_tail_pointer(skb, skb_headlen(skb));
skb_headers_offset_update(skb, 0);
skb->cloned = 0;
skb->hdr_len = 0;
skb->nohdr = 0;
atomic_set(&skb_shinfo(skb)->dataref, 1);
return 0;
}
static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
/* carve out the first eat bytes from skb's frag_list. May recurse into
* pskb_carve()
*/
static int pskb_carve_frag_list(struct sk_buff *skb,
struct skb_shared_info *shinfo, int eat,
gfp_t gfp_mask)
{
struct sk_buff *list = shinfo->frag_list;
struct sk_buff *clone = NULL;
struct sk_buff *insp = NULL;
do {
if (!list) {
pr_err("Not enough bytes to eat. Want %d\n", eat);
return -EFAULT;
}
if (list->len <= eat) {
/* Eaten as whole. */
eat -= list->len;
list = list->next;
insp = list;
} else {
/* Eaten partially. */
if (skb_shared(list)) {
clone = skb_clone(list, gfp_mask);
if (!clone)
return -ENOMEM;
insp = list->next;
list = clone;
} else {
/* This may be pulled without problems. */
insp = list;
}
if (pskb_carve(list, eat, gfp_mask) < 0) {
kfree_skb(clone);
return -ENOMEM;
}
break;
}
} while (eat);
/* Free pulled out fragments. */
while ((list = shinfo->frag_list) != insp) {
shinfo->frag_list = list->next;
kfree_skb(list);
}
/* And insert new clone at head. */
if (clone) {
clone->next = list;
shinfo->frag_list = clone;
}
return 0;
}
/* carve off first len bytes from skb. Split line (off) is in the
* non-linear part of skb
*/
static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
int pos, gfp_t gfp_mask)
{
int i, k = 0;
int size = skb_end_offset(skb);
u8 *data;
const int nfrags = skb_shinfo(skb)->nr_frags;
struct skb_shared_info *shinfo;
size = SKB_DATA_ALIGN(size);
if (skb_pfmemalloc(skb))
gfp_mask |= __GFP_MEMALLOC;
data = kmalloc_reserve(size +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
gfp_mask, NUMA_NO_NODE, NULL);
if (!data)
return -ENOMEM;
size = SKB_WITH_OVERHEAD(ksize(data));
memcpy((struct skb_shared_info *)(data + size),
skb_shinfo(skb), offsetof(struct skb_shared_info,
frags[skb_shinfo(skb)->nr_frags]));
if (skb_orphan_frags(skb, gfp_mask)) {
kfree(data);
return -ENOMEM;
}
shinfo = (struct skb_shared_info *)(data + size);
for (i = 0; i < nfrags; i++) {
int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
if (pos + fsize > off) {
shinfo->frags[k] = skb_shinfo(skb)->frags[i];
if (pos < off) {
/* Split frag.
* We have two variants in this case:
* 1. Move all the frag to the second
* part, if it is possible. F.e.
* this approach is mandatory for TUX,
* where splitting is expensive.
* 2. Split is accurately. We make this.
*/
shinfo->frags[0].page_offset += off - pos;
skb_frag_size_sub(&shinfo->frags[0], off - pos);
}
skb_frag_ref(skb, i);
k++;
}
pos += fsize;
}
shinfo->nr_frags = k;
if (skb_has_frag_list(skb))
skb_clone_fraglist(skb);
if (k == 0) {
/* split line is in frag list */
pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask);
}
skb_release_data(skb);
skb->head = data;
skb->head_frag = 0;
skb->data = data;
#ifdef NET_SKBUFF_DATA_USES_OFFSET
skb->end = size;
#else
skb->end = skb->head + size;
#endif
skb_reset_tail_pointer(skb);
skb_headers_offset_update(skb, 0);
skb->cloned = 0;
skb->hdr_len = 0;
skb->nohdr = 0;
skb->len -= off;
skb->data_len = skb->len;
atomic_set(&skb_shinfo(skb)->dataref, 1);
return 0;
}
/* remove len bytes from the beginning of the skb */
static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
{
int headlen = skb_headlen(skb);
if (len < headlen)
return pskb_carve_inside_header(skb, len, headlen, gfp);
else
return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
}
/* Extract to_copy bytes starting at off from skb, and return this in
* a new skb
*/
struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
int to_copy, gfp_t gfp)
{
struct sk_buff *clone = skb_clone(skb, gfp);
if (!clone)
return NULL;
if (pskb_carve(clone, off, gfp) < 0 ||
pskb_trim(clone, to_copy)) {
kfree_skb(clone);
return NULL;
}
return clone;
}
EXPORT_SYMBOL(pskb_extract);
/**
* skb_condense - try to get rid of fragments/frag_list if possible
* @skb: buffer
*
* Can be used to save memory before skb is added to a busy queue.
* If packet has bytes in frags and enough tail room in skb->head,
* pull all of them, so that we can free the frags right now and adjust
* truesize.
* Notes:
* We do not reallocate skb->head thus can not fail.
* Caller must re-evaluate skb->truesize if needed.
*/
void skb_condense(struct sk_buff *skb)
{
if (skb->data_len) {
if (skb->data_len > skb->end - skb->tail ||
skb_cloned(skb))
return;
/* Nice, we can free page frag(s) right now */
__pskb_pull_tail(skb, skb->data_len);
}
/* At this point, skb->truesize might be over estimated,
* because skb had a fragment, and fragments do not tell
* their truesize.
* When we pulled its content into skb->head, fragment
* was freed, but __pskb_pull_tail() could not possibly
* adjust skb->truesize, not knowing the frag truesize.
*/
skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3254_1 |
crossvul-cpp_data_bad_139_0 | /* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */
#if 0
http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf
https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set
#endif
#include <string.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
static RDESContext desctx;
typedef struct _cpu_const_tag {
const char *const key;
ut8 type;
ut32 value;
ut8 size;
} CPU_CONST;
#define CPU_CONST_NONE 0
#define CPU_CONST_PARAM 1
#define CPU_CONST_REG 2
typedef struct _cpu_model_tag {
const char *const model;
int pc;
char *inherit;
struct _cpu_model_tag *inherit_cpu_p;
CPU_CONST *consts[10];
} CPU_MODEL;
typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu);
typedef struct _opcodes_tag_ {
const char *const name;
int mask;
int selector;
inst_handler_t handler;
int cycles;
int size;
ut64 type;
} OPCODE_DESC;
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu);
#define CPU_MODEL_DECL(model, pc, consts) \
{ \
model, \
pc, \
consts \
}
#define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits))))
#define CPU_PC_MASK(cpu) MASK((cpu)->pc)
#define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0))
#define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu)
#define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T }
#define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK }
#define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu)
#define INST_INVALID { *fail = 1; return; }
#define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } }
#define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__)
#define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s))
// Following IO definitions are valid for:
// ATmega8
// ATmega88
CPU_CONST cpu_reg_common[] = {
{ "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) },
{ "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) },
{ "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) },
{ "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_common[] = {
{ "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = {
{ "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_xmega128a4u[] = {
{ "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_pagesize_5_bits[] = {
{ "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_pagesize_7_bits[] = {
{ "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_MODEL cpu_models[] = {
{ .model = "ATmega640", .pc = 15,
.consts = {
cpu_reg_common,
cpu_memsize_m640_m1280m_m1281_m2560_m2561,
cpu_pagesize_7_bits,
NULL
},
},
{
.model = "ATxmega128a4u", .pc = 17,
.consts = {
cpu_reg_common,
cpu_memsize_xmega128a4u,
cpu_pagesize_7_bits,
NULL
}
},
{ .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" },
{ .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" },
{ .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" },
{ .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" },
{ .model = "ATmega88", .pc = 8, .inherit = "ATmega8" },
// CPU_MODEL_DECL ("ATmega168", 13, 512, 512),
// last model is the default AVR - ATmega8 forever!
{
.model = "ATmega8", .pc = 13,
.consts = {
cpu_reg_common,
cpu_memsize_common,
cpu_pagesize_5_bits,
NULL
}
},
};
static CPU_MODEL *get_cpu_model(char *model);
static CPU_MODEL *__get_cpu_model_recursive(char *model) {
CPU_MODEL *cpu = NULL;
for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) {
if (!strcasecmp (model, cpu->model)) {
break;
}
}
// fix inheritance tree
if (cpu->inherit && !cpu->inherit_cpu_p) {
cpu->inherit_cpu_p = get_cpu_model (cpu->inherit);
if (!cpu->inherit_cpu_p) {
eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit);
}
}
return cpu;
}
static CPU_MODEL *get_cpu_model(char *model) {
static CPU_MODEL *cpu = NULL;
// cached value?
if (cpu && !strcasecmp (model, cpu->model))
return cpu;
// do the real search
cpu = __get_cpu_model_recursive (model);
return cpu;
}
static ut32 const_get_value(CPU_CONST *c) {
return c ? MASK (c->size * 8) & c->value : 0;
}
static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) {
CPU_CONST **clist, *citem;
for (clist = cpu->consts; *clist; clist++) {
for (citem = *clist; citem->key; citem++) {
if (!strcmp (c, citem->key)
&& (type == CPU_CONST_NONE || type == citem->type)) {
return citem;
}
}
}
if (cpu->inherit_cpu_p)
return const_by_name (cpu->inherit_cpu_p, type, c);
eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c);
return NULL;
}
static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) {
char *t = r_anal_esil_pop (esil);
if (!t || !r_anal_esil_get_parm (esil, t, v)) {
free (t);
return false;
}
free (t);
return true;
}
static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) {
CPU_CONST **clist, *citem;
for (clist = cpu->consts; *clist; clist++) {
for (citem = *clist; citem && citem->key; citem++) {
if (citem->value == (MASK (citem->size * 8) & v)
&& (type == CPU_CONST_NONE || type == citem->type)) {
return citem;
}
}
}
if (cpu->inherit_cpu_p)
return const_by_value (cpu->inherit_cpu_p, type, v);
return NULL;
}
static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) {
RStrBuf *r = r_strbuf_new ("");
CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port);
if (c != NULL) {
r_strbuf_set (r, c->key);
if (write) {
r_strbuf_append (r, ",=");
}
} else {
r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : "");
}
return r;
}
static void __generic_bitop_flags(RAnalOp *op) {
ESIL_A ("0,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
}
static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) {
if (ireg) {
// preincrement index register
if (prepostdec < 0) {
ESIL_A ("1,%c,-,%c,=,", ireg, ireg);
}
// set register index address
ESIL_A ("%c,", ireg);
// add offset
if (offset != 0) {
ESIL_A ("%d,+,", offset);
}
} else {
ESIL_A ("%d,", offset);
}
if (use_ramp) {
ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd');
}
// set SRAM base address
ESIL_A ("_%s,+,", mem);
// read/write from SRAM
ESIL_A ("%s[1],", st ? "=" : "");
// postincrement index register
if (ireg && prepostdec > 0) {
ESIL_A ("1,%c,+,%c,=,", ireg, ireg);
}
}
static void __generic_pop(RAnalOp *op, int sz) {
if (sz > 1) {
ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1)
ESIL_A ("[%d],", sz); // read value
ESIL_A ("%d,sp,+=,", sz); // sp += item_size
} else {
ESIL_A ("1,sp,+=," // increment stack pointer
"sp,_ram,+,[1],"); // load SRAM[sp]
}
}
static void __generic_push(RAnalOp *op, int sz) {
ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp)
if (sz > 1) {
ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz'
}
ESIL_A ("=[%d],", sz); // store value in stack
ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer
}
static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) {
RStrBuf *d_strbuf, *rk_strbuf;
char *d, *rk;
d_strbuf = r_strbuf_new (NULL);
rk_strbuf = r_strbuf_new (NULL);
r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d);
r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk);
d = r_strbuf_get(d_strbuf);
rk = r_strbuf_get(rk_strbuf);
ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&,"
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&,"
"|,|,hf,=,",
d, rk, rk, d);
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V
"" "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!," "%s,0x80,&,!," "&,"
"" "0,RPICK,0x80,&,!,!," "&,"
"|,vf,=,",
d, rk, d, rk);
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&,"
"|,|,cf,=,",
d, rk, rk, d);
ESIL_A ("vf,nf,^,sf,=,"); // S
r_strbuf_free (d_strbuf);
r_strbuf_free (rk_strbuf);
}
static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) {
__generic_add_update_flags(op, 'r', d, 'r', r);
}
static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) {
RStrBuf *d_strbuf, *rk_strbuf;
char *d, *rk;
d_strbuf = r_strbuf_new (NULL);
rk_strbuf = r_strbuf_new (NULL);
r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d);
r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk);
d = r_strbuf_get(d_strbuf);
rk = r_strbuf_get(rk_strbuf);
ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&,"
"%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&,"
"|,|,hf,=,",
d, rk, rk, d);
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V
"" "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!," "%s,0x80,&,!,!," "&,"
"" "0,RPICK,0x80,&,!,!," "&,"
"|,vf,=,",
d, rk, d, rk);
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
if (carry)
ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z
else
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&,"
"%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&,"
"|,|,cf,=,",
d, rk, rk, d);
ESIL_A ("vf,nf,^,sf,=,"); // S
r_strbuf_free (d_strbuf);
r_strbuf_free (rk_strbuf);
}
static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) {
__generic_sub_update_flags(op, 'r', d, 'r', r, carry);
}
static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) {
__generic_sub_update_flags(op, 'r', d, 'k', k, carry);
}
INST_HANDLER (adc) { // ADC Rd, Rr
// ROL Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C
__generic_add_update_flags_rr(op, d, r); // FLAGS
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (add) { // ADD Rd, Rr
// LSL Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr
__generic_add_update_flags_rr(op, d, r); // FLAGS
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr
// FLAGS:
ESIL_A ("r%d,0x80,&,!," // V
"0,RPICK,0x8000,&,!,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!,!," // C
"0,RPICK,0x8000,&,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
INST_HANDLER (and) { // AND Rd, Rr
// TST Rd
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (andi) { // ANDI Rd, K
// CBR Rd, K (= ANDI Rd, 1-K)
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f);
op->val = k;
ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (asr) { // ASR Rd
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7
ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("nf,vf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = R
}
INST_HANDLER (bclr) { // BCLR s
// CLC
// CLH
// CLI
// CLN
// CLR
// CLS
// CLT
// CLV
// CLZ
int s = (buf[0] >> 4) & 0x7;
ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s);
}
INST_HANDLER (bld) { // BLD Rd, b
if (len < 2) {
return;
}
int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf);
int b = buf[0] & 0x7;
ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0
ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b
}
INST_HANDLER (brbx) { // BRBC s, k
// BRBS s, k
// BRBC/S 0: BRCC BRCS
// BRSH BRLO
// BRBC/S 1: BREQ BRNE
// BRBC/S 2: BRPL BRMI
// BRBC/S 3: BRVC BRVS
// BRBC/S 4: BRGE BRLT
// BRBC/S 5: BRHC BRHS
// BRBC/S 6: BRTC BRTS
// BRBC/S 7: BRID BRIE
int s = buf[0] & 0x7;
op->jump = op->addr
+ ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2))
| (buf[1] & 0x2 ? ~((int) 0x7f) : 0))
+ 2;
op->fail = op->addr + op->size;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to true, this instruction
// needs 2 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s)
ESIL_A (buf[1] & 0x4
? "!," // BRBC => branch if cleared
: "!,!,"); // BRBS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (break) { // BREAK
ESIL_A ("BREAK");
}
INST_HANDLER (bset) { // BSET s
// SEC
// SEH
// SEI
// SEN
// SER
// SES
// SET
// SEV
// SEZ
int s = (buf[0] >> 4) & 0x7;
ESIL_A ("%d,1,<<,sreg,|=,", s);
}
INST_HANDLER (bst) { // BST Rd, b
if (len < 2) {
return;
}
ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b
((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r
buf[0] & 0x7); // b
}
INST_HANDLER (call) { // CALL k
if (len < 4) {
return;
}
op->jump = (buf[2] << 1)
| (buf[3] << 9)
| (buf[1] & 0x01) << 23
| (buf[0] & 0x01) << 17
| (buf[0] & 0xf0) << 14;
op->fail = op->addr + op->size;
op->cycles = cpu->pc <= 16 ? 3 : 4;
if (!STR_BEGINS (cpu->model, "ATxmega")) {
op->cycles--; // AT*mega optimizes one cycle
}
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
}
INST_HANDLER (cbi) { // CBI A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RStrBuf *io_port;
op->family = R_ANAL_OP_FAMILY_IO;
op->type2 = 1;
op->val = a;
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port);
r_strbuf_free (io_port);
// write result to port a
io_port = __generic_io_dest (a, 1, cpu);
ESIL_A ("%s,", r_strbuf_get (io_port));
r_strbuf_free (io_port);
}
INST_HANDLER (com) { // COM Rd
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4);
ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd
// FLAGS:
ESIL_A ("0,cf,=,"); // C
__generic_bitop_flags (op); // ...rest...
}
INST_HANDLER (cp) { // CP Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10);
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr
__generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry)
}
INST_HANDLER (cpc) { // CPC Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10);
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C
__generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry)
}
INST_HANDLER (cpi) { // CPI Rd, K
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4);
ESIL_A ("%d,r%d,-,", k, d); // Rd - k
__generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry)
}
INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to true, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (dec) { // DEC Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("-1,r%d,+,", d); // --Rd
// FLAGS:
ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (des) { // DES k
if (desctx.round < 16) { //DES
op->type = R_ANAL_OP_TYPE_CRYPTO;
op->cycles = 1; //redo this
r_strbuf_setf (&op->esil, "%d,des", desctx.round);
}
}
INST_HANDLER (eijmp) { // EIJMP
ut64 z, eind;
// read z and eind for calculating jump address on runtime
r_anal_esil_reg_read (anal->esil, "z", &z, NULL);
r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL);
// real target address may change during execution, so this value will
// be changing all the time
op->jump = ((eind << 16) + z) << 1;
// jump
ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,");
// cycles
op->cycles = 2;
}
INST_HANDLER (eicall) { // EICALL
// push pc in stack
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
// do a standard EIJMP
INST_CALL (eijmp);
// fix cycles
op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4;
}
INST_HANDLER (elpm) { // ELPM
// ELPM Rd
// ELPM Rd, Z+
int d = ((buf[1] & 0xfe) == 0x90)
? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd
: 0; // R0
ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z
ESIL_A ("r%d,=,", d); // Rd = [1]
if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) {
ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z)
}
}
INST_HANDLER (eor) { // EOR Rd, Rr
// CLR Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (fmul) { // FMUL Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (fmuls) { // FMULS Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,");
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr
ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (fmulsu) { // FMULSU Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,");
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("r%d", r); // unsigned Rr
ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (ijmp) { // IJMP k
ut64 z;
// read z for calculating jump address on runtime
r_anal_esil_reg_read (anal->esil, "z", &z, NULL);
// real target address may change during execution, so this value will
// be changing all the time
op->jump = z << 1;
op->cycles = 2;
ESIL_A ("1,z,<<,pc,=,"); // jump!
}
INST_HANDLER (icall) { // ICALL k
// push pc in stack
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
// do a standard IJMP
INST_CALL (ijmp);
// fix cycles
if (!STR_BEGINS (cpu->model, "ATxmega")) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (in) { // IN Rd, A
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4);
int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3);
RStrBuf *io_src = __generic_io_dest (a, 0, cpu);
op->type2 = 0;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r);
r_strbuf_free (io_src);
}
INST_HANDLER (inc) { // INC Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("1,r%d,+,", d); // ++Rd
// FLAGS:
ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (jmp) { // JMP k
op->jump = (buf[2] << 1)
| (buf[3] << 9)
| (buf[1] & 0x01) << 23
| (buf[0] & 0x01) << 17
| (buf[0] & 0xf0) << 14;
op->cycles = 3;
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
}
INST_HANDLER (lac) { // LAC Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (las) { // LAS Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,|,", d); // 0: (Z) | Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (lat) { // LAT Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (ld) { // LD Rd, X
// LD Rd, X+
// LD Rd, -X
// read memory
__generic_ld_st (
op, "ram",
'x', // use index register X
0, // no use RAMP* registers
(buf[0] & 0xf) == 0xe
? -1 // pre decremented
: (buf[0] & 0xf) == 0xd
? 1 // post incremented
: 0, // no increment
0, // offset always 0
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// cycles
op->cycles = (buf[0] & 0x3) == 0
? 2 // LD Rd, X
: (buf[0] & 0x3) == 1
? 2 // LD Rd, X+
: 3; // LD Rd, -X
if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z
// LD Rd, Y+ LD Rd, Z+
// LD Rd, -Y LD Rd, -Z
// LD Rd, Y+q LD Rd, Z+q
// calculate offset (this value only has sense in some opcodes,
// but we are optimistic and we calculate it always)
int offset = (buf[1] & 0x20)
| ((buf[1] & 0xc) << 1)
| (buf[0] & 0x7);
// read memory
__generic_ld_st (
op, "ram",
buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z
0, // no use RAMP* registers
!(buf[1] & 0x10)
? 0 // no increment
: buf[0] & 0x1
? 1 // post incremented
: -1, // pre decremented
!(buf[1] & 0x10) ? offset : 0, // offset or not offset
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// cycles
op->cycles =
(buf[1] & 0x10) == 0
? (!offset ? 1 : 3) // LDD
: (buf[0] & 0x3) == 0
? 1 // LD Rd, X
: (buf[0] & 0x3) == 1
? 2 // LD Rd, X+
: 3; // LD Rd, -X
if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (ldi) { // LDI Rd, K
int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4);
int d = ((buf[0] >> 4) & 0xf) + 16;
op->val = k;
ESIL_A ("0x%x,r%d,=,", k, d);
}
INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
// load value from RAMPD:k
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
#if 0
INST_HANDLER (lds16) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0x0f)
| ((buf[1] << 3) & 0x30)
| ((buf[1] << 4) & 0x40)
| (~(buf[1] << 4) & 0x80);
op->ptr = k;
// load value from @k
__generic_ld_st (op, "ram", 0, 0, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
#endif
INST_HANDLER (lpm) { // LPM
// LPM Rd, Z
// LPM Rd, Z+
ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]);
// read program memory
__generic_ld_st (
op, "prog",
'z', // index register Y/Z
1, // use RAMP* registers
(ins & 0xfe0f) == 0x9005
? 1 // post incremented
: 0, // no increment
0, // not offset
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,",
(ins == 0x95c8)
? 0 // LPM (r0)
: ((buf[0] >> 4) & 0xf) // LPM Rd
| ((buf[1] & 0x1) << 4));
}
INST_HANDLER (lsr) { // LSR Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1)
ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("nf,vf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = R
}
INST_HANDLER (mov) { // MOV Rd, Rr
int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f);
int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f);
ESIL_A ("r%d,r%d,=,", r, d);
}
INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr
int d = (buf[0] & 0xf0) >> 3;
int r = (buf[0] & 0x0f) << 1;
ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1);
}
INST_HANDLER (mul) { // MUL Rd, Rr
int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f);
int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f);
ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (muls) { // MULS Rd, Rr
int d = (buf[0] >> 4 & 0x0f) + 16;
int r = (buf[0] & 0x0f) + 16;
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("*,"); // 0: (Rd*Rr)
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (mulsu) { // MULSU Rd, Rr
int d = (buf[0] >> 4 & 0x07) + 16;
int r = (buf[0] & 0x07) + 16;
ESIL_A ("r%d,", r); // unsigned Rr
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("*,"); // 0: (Rd*Rr)
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (neg) { // NEG Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd)
ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H
ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V
ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N
ESIL_A ("DUP,!,zf,=,"); // Z
ESIL_A ("DUP,!,!,cf,=,"); // C
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (nop) { // NOP
ESIL_A (",,");
}
INST_HANDLER (or) { // OR Rd, Rr
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr)
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,vf,=,"); // V
ESIL_A ("nf,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (ori) { // ORI Rd, K
// SBR Rd, K
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4);
op->val = k;
ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k)
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,vf,=,"); // V
ESIL_A ("nf,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (out) { // OUT A, Rr
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4);
int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3);
RStrBuf *io_dst = __generic_io_dest (a, 1, cpu);
op->type2 = 1;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst));
r_strbuf_free (io_dst);
}
INST_HANDLER (pop) { // POP Rd
int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
__generic_pop (op, 1);
ESIL_A ("r%d,=,", d); // store in Rd
}
INST_HANDLER (push) { // PUSH Rr
int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
ESIL_A ("r%d,", r); // load Rr
__generic_push (op, 1); // push it into stack
// cycles
op->cycles = !STR_BEGINS (cpu->model, "ATxmega")
? 1 // AT*mega optimizes one cycle
: 2;
}
INST_HANDLER (rcall) { // RCALL k
// target address
op->jump = (op->addr
+ (((((buf[1] & 0xf) << 8) | buf[0]) << 1)
| (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0)))
+ 2) & CPU_PC_MASK (cpu);
op->fail = op->addr + op->size;
// esil
ESIL_A ("pc,"); // esil already points to next
// instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
// cycles
if (!strncasecmp (cpu->model, "ATtiny", 6)) {
op->cycles = 4; // ATtiny is always slow
} else {
// PC size decides required runtime!
op->cycles = cpu->pc <= 16 ? 3 : 4;
if (!STR_BEGINS (cpu->model, "ATxmega")) {
op->cycles--; // ATxmega optimizes one cycle
}
}
}
INST_HANDLER (ret) { // RET
op->eob = true;
// esil
__generic_pop (op, CPU_PC_SIZE (cpu));
ESIL_A ("pc,=,"); // jump!
// cycles
if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit
op->cycles++; // (i.e. a 22-bit bus), add one extra cycle
}
}
INST_HANDLER (reti) { // RETI
//XXX: There are not privileged instructions in ATMEL/AVR
op->family = R_ANAL_OP_FAMILY_PRIV;
// first perform a standard 'ret'
INST_CALL (ret);
// RETI: The I-bit is cleared by hardware after an interrupt
// has occurred, and is set by the RETI instruction to enable
// subsequent interrupts
ESIL_A ("1,if,=,");
}
INST_HANDLER (rjmp) { // RJMP k
op->jump = (op->addr
#ifdef _MSC_VER
#pragma message ("anal_avr.c: WARNING: Probably broken on windows")
+ ((((( buf[1] & 0xf) << 9) | (buf[0] << 1)))
| (buf[1] & 0x8 ? ~(0x1fff) : 0))
#else
+ ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1)))
| (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0))
#endif
+ 2) & CPU_PC_MASK (cpu);
ESIL_A ("%"PFMT64d",pc,=,", op->jump);
}
INST_HANDLER (ror) { // ROR Rd
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7)
ESIL_A ("r%d,1,&,cf,=,", d); // C
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (sbc) { // SBC Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C)
__generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sbci) { // SBCI Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf);
op->val = k;
ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C)
__generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sub) { // SUB Rd, Rr
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k)
__generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (subi) { // SUBI Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf);
op->val = k;
ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k)
__generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sbi) { // SBI A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RStrBuf *io_port;
op->type2 = 1;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port);
r_strbuf_free (io_port);
// write result to port a
io_port = __generic_io_dest (a, 1, cpu);
ESIL_A ("%s,", r_strbuf_get (io_port));
r_strbuf_free (io_port);
}
INST_HANDLER (sbix) { // SBIC A, b
// SBIS A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RAnalOp next_op;
RStrBuf *io_port;
op->type2 = 0;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size,
len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBIC => branch if 0
: "!,!,"); // SBIS => branch if 1
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
r_strbuf_free (io_port);
}
INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr)
ESIL_A ("r%d,0x80,&,!,!," // V
"0,RPICK,0x8000,&,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!," // C
"0,RPICK,0x8000,&,!,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
INST_HANDLER (sbrx) { // SBRC Rr, b
// SBRS Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op = {0};
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (sleep) { // SLEEP
ESIL_A ("BREAK");
}
INST_HANDLER (spm) { // SPM Z+
ut64 spmcsr;
// read SPM Control Register (SPMCR)
r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL);
// clear SPMCSR
ESIL_A ("0x7c,spmcsr,&=,");
// decide action depending on the old value of SPMCSR
switch (spmcsr & 0x7f) {
case 0x03: // PAGE ERASE
// invoke SPM_CLEAR_PAGE (erases target page writing
// the 0xff value
ESIL_A ("16,rampz,<<,z,+,"); // push target address
ESIL_A ("SPM_PAGE_ERASE,"); // do magic
break;
case 0x01: // FILL TEMPORARY BUFFER
ESIL_A ("r1,r0,"); // push data
ESIL_A ("z,"); // push target address
ESIL_A ("SPM_PAGE_FILL,"); // do magic
break;
case 0x05: // WRITE PAGE
ESIL_A ("16,rampz,<<,z,+,"); // push target address
ESIL_A ("SPM_PAGE_WRITE,"); // do magic
break;
default:
eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n",
(unsigned int) spmcsr);
}
op->cycles = 1; // This is truly false. Datasheets do not publish how
// many cycles this instruction uses in all its
// operation modes and I am pretty sure that this value
// can vary substantially from one MCU type to another.
// So... one cycle is fine.
}
INST_HANDLER (st) { // ST X, Rr
// ST X+, Rr
// ST -X, Rr
// load register
ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// write in memory
__generic_ld_st (
op, "ram",
'x', // use index register X
0, // no use RAMP* registers
(buf[0] & 0xf) == 0xe
? -1 // pre decremented
: (buf[0] & 0xf) == 0xd
? 1 // post increment
: 0, // no increment
0, // offset always 0
1); // store operation (st)
// // cycles
// op->cycles = buf[0] & 0x3 == 0
// ? 2 // LD Rd, X
// : buf[0] & 0x3 == 1
// ? 2 // LD Rd, X+
// : 3; // LD Rd, -X
// if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// // AT*mega optimizes 1 cycle!
// op->cycles--;
// }
}
INST_HANDLER (std) { // ST Y, Rr ST Z, Rr
// ST Y+, Rr ST Z+, Rr
// ST -Y, Rr ST -Z, Rr
// ST Y+q, Rr ST Z+q, Rr
// load register
ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// write in memory
__generic_ld_st (
op, "ram",
buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z
0, // no use RAMP* registers
!(buf[1] & 0x10)
? 0 // no increment
: buf[0] & 0x1
? 1 // post incremented
: -1, // pre decremented
!(buf[1] & 0x10)
? (buf[1] & 0x20) // offset
| ((buf[1] & 0xc) << 1)
| (buf[0] & 0x7)
: 0, // no offset
1); // load operation (!st)
// // cycles
// op->cycles =
// buf[1] & 0x1 == 0
// ? !(offset ? 1 : 3) // LDD
// : buf[0] & 0x3 == 0
// ? 1 // LD Rd, X
// : buf[0] & 0x3 == 1
// ? 2 // LD Rd, X+
// : 3; // LD Rd, -X
// if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// // AT*mega optimizes 1 cycle!
// op->cycles--;
// }
}
INST_HANDLER (swap) { // SWAP Rd
int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf
ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf
ESIL_A ("|,", d); // S[0] | S[1]
ESIL_A ("r%d,=,", d); // Rd = result
}
OPCODE_DESC opcodes[] = {
// op mask select cycles size type
INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK
INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL
INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP
INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL
INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP
INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM
INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP
INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET
INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI
INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP
INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ...
INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s
INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s
INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr
INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr
INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr
INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k
INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K
INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K
INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K
INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K
INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr
INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd
INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b
INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd
INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z
INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+
INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd
INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd
INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd
INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd
INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X
INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+
INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X
INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k
INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr
INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z
INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+
INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd
INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd
INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd
INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr
INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd
INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr
INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr
INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr
INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd
INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k
INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k
INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b
INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b
INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b
INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b
INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b
INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b
INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+
INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z
INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr
INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr
INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr
INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr
INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr
INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k
INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k
INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr
INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr
INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr
INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr
INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr
INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr
INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr
INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr
INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A
//INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k
INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr
INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K
INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K
INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K
INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K
INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k
INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k
INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr
INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr
INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q
INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr
INST_LAST
};
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
if (len < 2) {
return NULL;
}
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
// initialize op struct
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
// process opcode
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
// copy default cycles/size values
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
// op->fail = addr + op->size;
op->addr = addr;
// start void esil expression
r_strbuf_setf (&op->esil, "");
// handle opcode
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
// eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr);
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
// remove trailing coma (COMETE LA COMA)
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
// ignore reserved opcodes (if they have not been caught by the previous loop)
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
// An unknown or invalid option has appeared.
// -- Throw pokeball!
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
// launch esil trap (for communicating upper layers about this weird
// and stinky situation
r_strbuf_set (&op->esil, "1,$");
return NULL;
}
static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) {
CPU_MODEL *cpu;
ut64 offset;
// init op
if (!op) {
return 2;
}
// select cpu info
cpu = get_cpu_model (anal->cpu);
// set memory layout registers
if (anal->esil) {
offset = 0;
r_anal_esil_reg_write (anal->esil, "_prog", offset);
offset += (1 << cpu->pc);
r_anal_esil_reg_write (anal->esil, "_io", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start"));
r_anal_esil_reg_write (anal->esil, "_sram", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size"));
r_anal_esil_reg_write (anal->esil, "_eeprom", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size"));
r_anal_esil_reg_write (anal->esil, "_page", offset);
}
// process opcode
avr_op_analyze (anal, op, addr, buf, len, cpu);
return op->size;
}
static int avr_custom_des (RAnalEsil *esil) {
ut64 key, encrypt, text,des_round;
ut32 key_lo, key_hi, buf_lo, buf_hi;
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
if (!__esil_pop_argument (esil, &des_round)) {
return false;
}
r_anal_esil_reg_read (esil, "hf", &encrypt, NULL);
r_anal_esil_reg_read (esil, "deskey", &key, NULL);
r_anal_esil_reg_read (esil, "text", &text, NULL);
key_lo = key & UT32_MAX;
key_hi = key >> 32;
buf_lo = text & UT32_MAX;
buf_hi = text >> 32;
if (des_round != desctx.round) {
desctx.round = des_round;
}
if (!desctx.round) {
int i;
//generating all round keys
r_des_permute_key (&key_lo, &key_hi);
for (i = 0; i < 16; i++) {
r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi);
}
r_des_permute_block0 (&buf_lo, &buf_hi);
}
if (encrypt) {
r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]);
} else {
r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]);
}
if (desctx.round == 15) {
r_des_permute_block1 (&buf_hi, &buf_lo);
desctx.round = 0;
} else {
desctx.round++;
}
r_anal_esil_reg_write (esil, "text", text);
return true;
}
// ESIL operation SPM_PAGE_ERASE
static int avr_custom_spm_page_erase(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut8 c;
ut64 addr, page_size_bits, i;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
// get details about current MCU and fix input address
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
// align base address to page_size_bits
addr &= ~(MASK (page_size_bits));
// perform erase
//eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr);
c = 0xff;
for (i = 0; i < (1ULL << page_size_bits); i++) {
r_anal_esil_mem_write (
esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1);
}
return true;
}
// ESIL operation SPM_PAGE_FILL
static int avr_custom_spm_page_fill(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut64 addr, page_size_bits, i;
ut8 r0, r1;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address, r0, r1
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r0 = i;
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r1 = i;
// get details about current MCU and fix input address
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
// align and crop base address
addr &= (MASK (page_size_bits) ^ 1);
// perform write to temporary page
//eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr);
r_anal_esil_mem_write (esil, addr++, &r0, 1);
r_anal_esil_mem_write (esil, addr++, &r1, 1);
return true;
}
// ESIL operation SPM_PAGE_WRITE
static int avr_custom_spm_page_write(RAnalEsil *esil) {
CPU_MODEL *cpu;
char *t = NULL;
ut64 addr, page_size_bits, tmp_page;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address
if (!__esil_pop_argument (esil, &addr)) {
return false;
}
// get details about current MCU and fix input address and base address
// of the internal temporary page
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL);
// align base address to page_size_bits
addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu));
// perform writing
//eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr);
if (!(t = malloc (1 << page_size_bits))) {
eprintf ("Cannot alloc a buffer for copying the temporary page.\n");
return false;
}
r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits);
r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits);
return true;
}
static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) {
CPU_MODEL *cpu;
if (!esil || !esil->anal) {
return 0;
}
// select cpu info
cpu = get_cpu_model (esil->anal->cpu);
// crop registers and force certain values
if (!strcmp (name, "pc")) {
*val &= CPU_PC_MASK (cpu);
} else if (!strcmp (name, "pcl")) {
if (cpu->pc < 8) {
*val &= MASK (8);
}
} else if (!strcmp (name, "pch")) {
*val = cpu->pc > 8
? *val & MASK (cpu->pc - 8)
: 0;
}
return 0;
}
static int esil_avr_init(RAnalEsil *esil) {
if (!esil) {
return false;
}
desctx.round = 0;
r_anal_esil_set_op (esil, "des", avr_custom_des);
r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase);
r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill);
r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write);
esil->cb.hook_reg_write = esil_avr_hook_reg_write;
return true;
}
static int esil_avr_fini(RAnalEsil *esil) {
return true;
}
static int set_reg_profile(RAnal *anal) {
const char *p =
"=PC pcl\n"
"=SP sp\n"
// explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html
// and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file
"=A0 r25\n"
"=A1 r24\n"
"=A2 r23\n"
"=A3 r22\n"
"=R0 r24\n"
#if 0
PC: 16- or 22-bit program counter
SP: 8- or 16-bit stack pointer
SREG: 8-bit status register
RAMPX, RAMPY, RAMPZ, RAMPD and EIND:
#endif
// 8bit registers x 32
"gpr r0 .8 0 0\n"
"gpr r1 .8 1 0\n"
"gpr r2 .8 2 0\n"
"gpr r3 .8 3 0\n"
"gpr r4 .8 4 0\n"
"gpr r5 .8 5 0\n"
"gpr r6 .8 6 0\n"
"gpr r7 .8 7 0\n"
"gpr text .64 0 0\n"
"gpr r8 .8 8 0\n"
"gpr r9 .8 9 0\n"
"gpr r10 .8 10 0\n"
"gpr r11 .8 11 0\n"
"gpr r12 .8 12 0\n"
"gpr r13 .8 13 0\n"
"gpr r14 .8 14 0\n"
"gpr r15 .8 15 0\n"
"gpr deskey .64 8 0\n"
"gpr r16 .8 16 0\n"
"gpr r17 .8 17 0\n"
"gpr r18 .8 18 0\n"
"gpr r19 .8 19 0\n"
"gpr r20 .8 20 0\n"
"gpr r21 .8 21 0\n"
"gpr r22 .8 22 0\n"
"gpr r23 .8 23 0\n"
"gpr r24 .8 24 0\n"
"gpr r25 .8 25 0\n"
"gpr r26 .8 26 0\n"
"gpr r27 .8 27 0\n"
"gpr r28 .8 28 0\n"
"gpr r29 .8 29 0\n"
"gpr r30 .8 30 0\n"
"gpr r31 .8 31 0\n"
// 16 bit overlapped registers for 16 bit math
"gpr r17:r16 .16 16 0\n"
"gpr r19:r18 .16 18 0\n"
"gpr r21:r20 .16 20 0\n"
"gpr r23:r22 .16 22 0\n"
"gpr r25:r24 .16 24 0\n"
"gpr r27:r26 .16 26 0\n"
"gpr r29:r28 .16 28 0\n"
"gpr r31:r30 .16 30 0\n"
// 16 bit overlapped registers for memory addressing
"gpr x .16 26 0\n"
"gpr y .16 28 0\n"
"gpr z .16 30 0\n"
// program counter
// NOTE: program counter size in AVR depends on the CPU model. It seems that
// the PC may range from 16 bits to 22 bits.
"gpr pc .32 32 0\n"
"gpr pcl .16 32 0\n"
"gpr pch .16 34 0\n"
// special purpose registers
"gpr sp .16 36 0\n"
"gpr spl .8 36 0\n"
"gpr sph .8 37 0\n"
// status bit register (SREG)
"gpr sreg .8 38 0\n"
"gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts.
"gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero.
"gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result.
"gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow.
"gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison.
"gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic.
"gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit.
"gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled.
// 8bit segment registers to be added to X, Y, Z to get 24bit offsets
"gpr rampx .8 39 0\n"
"gpr rampy .8 40 0\n"
"gpr rampz .8 41 0\n"
"gpr rampd .8 42 0\n"
"gpr eind .8 43 0\n"
// memory mapping emulator registers
// _prog
// the program flash. It has its own address space.
// _ram
// _io
// start of the data addres space. It is the same address of IO,
// because IO is the first memory space addressable in the AVR.
// _sram
// start of the SRAM (this offset depends on IO size, and it is
// inside the _ram address space)
// _eeprom
// this is another address space, outside ram and flash
// _page
// this is the temporary page used by the SPM instruction. This
// memory is not directly addressable and it is used internally by
// the CPU when autoflashing.
"gpr _prog .32 44 0\n"
"gpr _page .32 48 0\n"
"gpr _eeprom .32 52 0\n"
"gpr _ram .32 56 0\n"
"gpr _io .32 56 0\n"
"gpr _sram .32 60 0\n"
// other important MCU registers
// spmcsr/spmcr
// Store Program Memory Control and Status Register (SPMCSR)
"gpr spmcsr .8 64 0\n"
;
return r_reg_set_profile_string (anal->reg, p);
}
static int archinfo(RAnal *anal, int q) {
if (q == R_ANAL_ARCHINFO_ALIGN)
return 2;
if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE)
return 4;
if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE)
return 2;
return 2; // XXX
}
static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) {
RAnalOp *op = NULL;
ut8 *ret = NULL;
int idx;
if (!(op = r_anal_op_new ())) {
return NULL;
}
if (!(ret = malloc (size))) {
r_anal_op_free (op);
return NULL;
}
memset (ret, 0xff, size);
CPU_MODEL *cpu = get_cpu_model (anal->cpu);
for (idx = 0; idx + 1 < size; idx += op->size) {
OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu);
if (op->size < 1) {
break;
}
if (!opcode_desc) { // invalid instruction
continue;
}
// the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching
// (things like memory offsets or jump addresses)
if (op->size == 4) {
ret[idx + 2] = 0;
ret[idx + 3] = 0;
}
if (op->ptr != UT64_MAX || op->jump != UT64_MAX) {
ret[idx] = opcode_desc->mask;
ret[idx + 1] = opcode_desc->mask >> 8;
}
}
r_anal_op_free (op);
return ret;
}
RAnalPlugin r_anal_plugin_avr = {
.name = "avr",
.desc = "AVR code analysis plugin",
.license = "LGPL3",
.arch = "avr",
.esil = true,
.archinfo = archinfo,
.bits = 8 | 16, // 24 big regs conflicts
.op = &avr_op,
.set_reg_profile = &set_reg_profile,
.esil_init = esil_avr_init,
.esil_fini = esil_avr_fini,
.anal_mask = anal_mask_avr,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
.data = &r_anal_plugin_avr,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_139_0 |
crossvul-cpp_data_good_3208_0 | /*
* Yerase's TNEF Stream Reader Library
* Copyright (C) 2003 Randall E. Hand
*
* 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
*
* You can contact me at randall.hand@gmail.com for questions or assistance
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include "ytnef.h"
#include "tnef-errors.h"
#include "mapi.h"
#include "mapidefs.h"
#include "mapitags.h"
#include "config.h"
#define RTF_PREBUF "{\\rtf1\\ansi\\mac\\deff0\\deftab720{\\fonttbl;}{\\f0\\fnil \\froman \\fswiss \\fmodern \\fscript \\fdecor MS Sans SerifSymbolArialTimes New RomanCourier{\\colortbl\\red0\\green0\\blue0\n\r\\par \\pard\\plain\\f0\\fs20\\b\\i\\u\\tab\\tx"
#define DEBUG(lvl, curlvl, msg) \
if ((lvl) >= (curlvl)) \
printf("DEBUG(%i/%i): %s\n", curlvl, lvl, msg);
#define DEBUG1(lvl, curlvl, msg, var1) \
if ((lvl) >= (curlvl)) { \
printf("DEBUG(%i/%i):", curlvl, lvl); \
printf(msg, var1); \
printf("\n"); \
}
#define DEBUG2(lvl, curlvl, msg, var1, var2) \
if ((lvl) >= (curlvl)) { \
printf("DEBUG(%i/%i):", curlvl, lvl); \
printf(msg, var1, var2); \
printf("\n"); \
}
#define DEBUG3(lvl, curlvl, msg, var1, var2, var3) \
if ((lvl) >= (curlvl)) { \
printf("DEBUG(%i/%i):", curlvl, lvl); \
printf(msg, var1, var2,var3); \
printf("\n"); \
}
#define MIN(x,y) (((x)<(y))?(x):(y))
#define ALLOCCHECK(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(-1); } }
#define ALLOCCHECK_CHAR(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(NULL); } }
#define SIZECHECK(x) { if ((((char *)d - (char *)data) + x) > size) { printf("Corrupted file detected at %s : %i\n", __FILE__, __LINE__); return(-1); } }
int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p);
void SetFlip(void);
int TNEFDefaultHandler STD_ARGLIST;
int TNEFAttachmentFilename STD_ARGLIST;
int TNEFAttachmentSave STD_ARGLIST;
int TNEFDetailedPrint STD_ARGLIST;
int TNEFHexBreakdown STD_ARGLIST;
int TNEFBody STD_ARGLIST;
int TNEFRendData STD_ARGLIST;
int TNEFDateHandler STD_ARGLIST;
int TNEFPriority STD_ARGLIST;
int TNEFVersion STD_ARGLIST;
int TNEFMapiProperties STD_ARGLIST;
int TNEFIcon STD_ARGLIST;
int TNEFSubjectHandler STD_ARGLIST;
int TNEFFromHandler STD_ARGLIST;
int TNEFRecipTable STD_ARGLIST;
int TNEFAttachmentMAPI STD_ARGLIST;
int TNEFSentFor STD_ARGLIST;
int TNEFMessageClass STD_ARGLIST;
int TNEFMessageID STD_ARGLIST;
int TNEFParentID STD_ARGLIST;
int TNEFOriginalMsgClass STD_ARGLIST;
int TNEFCodePage STD_ARGLIST;
BYTE *TNEFFileContents = NULL;
DWORD TNEFFileContentsSize;
BYTE *TNEFFileIcon = NULL;
DWORD TNEFFileIconSize;
int IsCompressedRTF(variableLength *p);
TNEFHandler TNEFList[] = {
{attNull, "Null", TNEFDefaultHandler},
{attFrom, "From", TNEFFromHandler},
{attSubject, "Subject", TNEFSubjectHandler},
{attDateSent, "Date Sent", TNEFDateHandler},
{attDateRecd, "Date Received", TNEFDateHandler},
{attMessageStatus, "Message Status", TNEFDefaultHandler},
{attMessageClass, "Message Class", TNEFMessageClass},
{attMessageID, "Message ID", TNEFMessageID},
{attParentID, "Parent ID", TNEFParentID},
{attConversationID, "Conversation ID", TNEFDefaultHandler},
{attBody, "Body", TNEFBody},
{attPriority, "Priority", TNEFPriority},
{attAttachData, "Attach Data", TNEFAttachmentSave},
{attAttachTitle, "Attach Title", TNEFAttachmentFilename},
{attAttachMetaFile, "Attach Meta-File", TNEFIcon},
{attAttachCreateDate, "Attachment Create Date", TNEFDateHandler},
{attAttachModifyDate, "Attachment Modify Date", TNEFDateHandler},
{attDateModified, "Date Modified", TNEFDateHandler},
{attAttachTransportFilename, "Attachment Transport name", TNEFDefaultHandler},
{attAttachRenddata, "Attachment Display info", TNEFRendData},
{attMAPIProps, "MAPI Properties", TNEFMapiProperties},
{attRecipTable, "Recip Table", TNEFRecipTable},
{attAttachment, "Attachment", TNEFAttachmentMAPI},
{attTnefVersion, "TNEF Version", TNEFVersion},
{attOemCodepage, "OEM CodePage", TNEFCodePage},
{attOriginalMessageClass, "Original Message Class", TNEFOriginalMsgClass},
{attOwner, "Owner", TNEFDefaultHandler},
{attSentFor, "Sent For", TNEFSentFor},
{attDelegate, "Delegate", TNEFDefaultHandler},
{attDateStart, "Date Start", TNEFDateHandler},
{attDateEnd, "Date End", TNEFDateHandler},
{attAidOwner, "Aid Owner", TNEFDefaultHandler},
{attRequestRes, "Request Response", TNEFDefaultHandler}
};
WORD SwapWord(BYTE *p, int size) {
union BYTES2WORD
{
WORD word;
BYTE bytes[sizeof(WORD)];
};
union BYTES2WORD converter;
converter.word = 0;
int i = 0;
int correct = size > sizeof(WORD) ? sizeof(WORD) : size;
#ifdef WORDS_BIGENDIAN
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[correct - i];
}
#else
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[i];
}
#endif
return converter.word;
}
DWORD SwapDWord(BYTE *p, int size) {
union BYTES2DWORD
{
DWORD dword;
BYTE bytes[sizeof(DWORD)];
};
union BYTES2DWORD converter;
converter.dword = 0;
int i = 0;
int correct = size > sizeof(DWORD) ? sizeof(DWORD) : size;
#ifdef WORDS_BIGENDIAN
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[correct - i];
}
#else
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[i];
}
#endif
return converter.dword;
}
DDWORD SwapDDWord(BYTE *p, int size) {
union BYTES2DDWORD
{
DDWORD ddword;
BYTE bytes[sizeof(DDWORD)];
};
union BYTES2DDWORD converter;
converter.ddword = 0;
int i = 0;
int correct = size > sizeof(DDWORD) ? sizeof(DDWORD) : size;
#ifdef WORDS_BIGENDIAN
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[correct - i];
}
#else
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[i];
}
#endif
return converter.ddword;
}
/* convert 16-bit unicode to UTF8 unicode */
char *to_utf8(size_t len, char *buf) {
int i, j = 0;
/* worst case length */
if (len > 10000) { // deal with this by adding an arbitrary limit
printf("suspecting a corrupt file in UTF8 conversion\n");
exit(-1);
}
char *utf8 = malloc(3 * len / 2 + 1);
for (i = 0; i < len - 1; i += 2) {
unsigned int c = SwapWord((BYTE *)buf + i, 2);
if (c <= 0x007f) {
utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
} else if (c < 0x07ff) {
utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
} else {
utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
}
}
/* just in case the original was not null terminated */
utf8[j++] = '\0';
return utf8;
}
// -----------------------------------------------------------------------------
int TNEFDefaultHandler STD_ARGLIST {
if (TNEF->Debug >= 1)
printf("%s: [%i] %s\n", TNEFList[id].name, size, data);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFCodePage STD_ARGLIST {
TNEF->CodePage.size = size;
TNEF->CodePage.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->CodePage.data);
memcpy(TNEF->CodePage.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFParentID STD_ARGLIST {
memcpy(TNEF->parentID, data, MIN(size, sizeof(TNEF->parentID)));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFMessageID STD_ARGLIST {
memcpy(TNEF->messageID, data, MIN(size, sizeof(TNEF->messageID)));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFBody STD_ARGLIST {
TNEF->body.size = size;
TNEF->body.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->body.data);
memcpy(TNEF->body.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFOriginalMsgClass STD_ARGLIST {
TNEF->OriginalMessageClass.size = size;
TNEF->OriginalMessageClass.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->OriginalMessageClass.data);
memcpy(TNEF->OriginalMessageClass.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFMessageClass STD_ARGLIST {
memcpy(TNEF->messageClass, data, MIN(size, sizeof(TNEF->messageClass)));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFFromHandler STD_ARGLIST {
TNEF->from.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->from.data);
TNEF->from.size = size;
memcpy(TNEF->from.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFSubjectHandler STD_ARGLIST {
if (TNEF->subject.data)
free(TNEF->subject.data);
TNEF->subject.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->subject.data);
TNEF->subject.size = size;
memcpy(TNEF->subject.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFRendData STD_ARGLIST {
Attachment *p;
// Find the last attachment.
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
// Add a new one
p->next = calloc(1, sizeof(Attachment));
ALLOCCHECK(p->next);
p = p->next;
TNEFInitAttachment(p);
int correct = (size >= sizeof(renddata)) ? sizeof(renddata) : size;
memcpy(&(p->RenderData), data, correct);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFVersion STD_ARGLIST {
WORD major;
WORD minor;
minor = SwapWord((BYTE*)data, size);
major = SwapWord((BYTE*)data + 2, size - 2);
snprintf(TNEF->version, sizeof(TNEF->version), "TNEF%i.%i", major, minor);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFIcon STD_ARGLIST {
Attachment *p;
// Find the last attachment.
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
p->IconData.size = size;
p->IconData.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(p->IconData.data);
memcpy(p->IconData.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFRecipTable STD_ARGLIST {
DWORD count;
BYTE *d;
int current_row;
int propcount;
int current_prop;
d = (BYTE*)data;
count = SwapDWord((BYTE*)d, 4);
d += 4;
// printf("Recipient Table containing %u rows\n", count);
return 0;
for (current_row = 0; current_row < count; current_row++) {
propcount = SwapDWord((BYTE*)d, 4);
if (TNEF->Debug >= 1)
printf("> Row %i contains %i properties\n", current_row, propcount);
d += 4;
for (current_prop = 0; current_prop < propcount; current_prop++) {
}
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFAttachmentMAPI STD_ARGLIST {
Attachment *p;
// Find the last attachment.
//
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
return TNEFFillMapi(TNEF, (BYTE*)data, size, &(p->MAPI));
}
// -----------------------------------------------------------------------------
int TNEFMapiProperties STD_ARGLIST {
if (TNEFFillMapi(TNEF, (BYTE*)data, size, &(TNEF->MapiProperties)) < 0) {
printf("ERROR Parsing MAPI block\n");
return -1;
};
if (TNEF->Debug >= 3) {
MAPIPrint(&(TNEF->MapiProperties));
}
return 0;
}
int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p) {
int i, j;
DWORD num;
BYTE *d;
MAPIProperty *mp;
DWORD type;
DWORD length;
variableLength *vl;
WORD temp_word;
DWORD temp_dword;
DDWORD temp_ddword;
int count = -1;
int offset;
d = data;
p->count = SwapDWord((BYTE*)data, 4);
d += 4;
p->properties = calloc(p->count, sizeof(MAPIProperty));
ALLOCCHECK(p->properties);
mp = p->properties;
for (i = 0; i < p->count; i++) {
if (count == -1) {
mp->id = SwapDWord((BYTE*)d, 4);
d += 4;
mp->custom = 0;
mp->count = 1;
mp->namedproperty = 0;
length = -1;
if (PROP_ID(mp->id) >= 0x8000) {
// Read the GUID
SIZECHECK(16);
memcpy(&(mp->guid[0]), d, 16);
d += 16;
SIZECHECK(4);
length = SwapDWord((BYTE*)d, 4);
d += sizeof(DWORD);
if (length > 0) {
mp->namedproperty = length;
mp->propnames = calloc(length, sizeof(variableLength));
ALLOCCHECK(mp->propnames);
while (length > 0) {
SIZECHECK(4);
type = SwapDWord((BYTE*)d, 4);
mp->propnames[length - 1].data = calloc(type, sizeof(BYTE));
ALLOCCHECK(mp->propnames[length - 1].data);
mp->propnames[length - 1].size = type;
d += 4;
for (j = 0; j < (type >> 1); j++) {
SIZECHECK(j*2);
mp->propnames[length - 1].data[j] = d[j * 2];
}
d += type + ((type % 4) ? (4 - type % 4) : 0);
length--;
}
} else {
// READ the type
SIZECHECK(sizeof(DWORD));
type = SwapDWord((BYTE*)d, sizeof(DWORD));
d += sizeof(DWORD);
mp->id = PROP_TAG(PROP_TYPE(mp->id), type);
}
mp->custom = 1;
}
DEBUG2(TNEF->Debug, 3, "Type id = %04x, Prop id = %04x", PROP_TYPE(mp->id),
PROP_ID(mp->id));
if (PROP_TYPE(mp->id) & MV_FLAG) {
mp->id = PROP_TAG(PROP_TYPE(mp->id) - MV_FLAG, PROP_ID(mp->id));
SIZECHECK(4);
mp->count = SwapDWord((BYTE*)d, 4);
d += 4;
count = 0;
}
mp->data = calloc(mp->count, sizeof(variableLength));
ALLOCCHECK(mp->data);
vl = mp->data;
} else {
i--;
count++;
vl = &(mp->data[count]);
}
switch (PROP_TYPE(mp->id)) {
case PT_BINARY:
case PT_OBJECT:
case PT_STRING8:
case PT_UNICODE:
// First number of objects (assume 1 for now)
if (count == -1) {
SIZECHECK(4);
vl->size = SwapDWord((BYTE*)d, 4);
d += 4;
}
// now size of object
SIZECHECK(4);
vl->size = SwapDWord((BYTE*)d, 4);
d += 4;
// now actual object
if (vl->size != 0) {
SIZECHECK(vl->size);
if (PROP_TYPE(mp->id) == PT_UNICODE) {
vl->data =(BYTE*) to_utf8(vl->size, (char*)d);
} else {
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
memcpy(vl->data, d, vl->size);
}
} else {
vl->data = NULL;
}
// Make sure to read in a multiple of 4
num = vl->size;
offset = ((num % 4) ? (4 - num % 4) : 0);
d += num + ((num % 4) ? (4 - num % 4) : 0);
break;
case PT_I2:
// Read in 2 bytes, but proceed by 4 bytes
vl->size = 2;
vl->data = calloc(vl->size, sizeof(WORD));
ALLOCCHECK(vl->data);
SIZECHECK(sizeof(WORD))
temp_word = SwapWord((BYTE*)d, sizeof(WORD));
memcpy(vl->data, &temp_word, vl->size);
d += 4;
break;
case PT_BOOLEAN:
case PT_LONG:
case PT_R4:
case PT_CURRENCY:
case PT_APPTIME:
case PT_ERROR:
vl->size = 4;
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
SIZECHECK(4);
temp_dword = SwapDWord((BYTE*)d, 4);
memcpy(vl->data, &temp_dword, vl->size);
d += 4;
break;
case PT_DOUBLE:
case PT_I8:
case PT_SYSTIME:
vl->size = 8;
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
SIZECHECK(8);
temp_ddword = SwapDDWord(d, 8);
memcpy(vl->data, &temp_ddword, vl->size);
d += 8;
break;
case PT_CLSID:
vl->size = 16;
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
SIZECHECK(vl->size);
memcpy(vl->data, d, vl->size);
d+=16;
break;
default:
printf("Bad file\n");
exit(-1);
}
switch (PROP_ID(mp->id)) {
case PR_SUBJECT:
case PR_SUBJECT_IPM:
case PR_ORIGINAL_SUBJECT:
case PR_NORMALIZED_SUBJECT:
case PR_CONVERSATION_TOPIC:
DEBUG(TNEF->Debug, 3, "Got a Subject");
if (TNEF->subject.size == 0) {
int i;
DEBUG(TNEF->Debug, 3, "Assigning a Subject");
TNEF->subject.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->subject.data);
TNEF->subject.size = vl->size;
memcpy(TNEF->subject.data, vl->data, vl->size);
// Unfortunately, we have to normalize out some invalid
// characters, or else the file won't write
for (i = 0; i != TNEF->subject.size; i++) {
switch (TNEF->subject.data[i]) {
case '\\':
case '/':
case '\0':
TNEF->subject.data[i] = '_';
break;
}
}
}
break;
}
if (count == (mp->count - 1)) {
count = -1;
}
if (count == -1) {
mp++;
}
}
if ((d - data) < size) {
if (TNEF->Debug >= 1) {
printf("ERROR DURING MAPI READ\n");
printf("Read %td bytes, Expected %u bytes\n", (d - data), size);
printf("%td bytes missing\n", size - (d - data));
}
} else if ((d - data) > size) {
if (TNEF->Debug >= 1) {
printf("ERROR DURING MAPI READ\n");
printf("Read %td bytes, Expected %u bytes\n", (d - data), size);
printf("%li bytes extra\n", (d - data) - size);
}
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFSentFor STD_ARGLIST {
WORD name_length, addr_length;
BYTE *d;
d = (BYTE*)data;
while ((d - (BYTE*)data) < size) {
SIZECHECK(sizeof(WORD));
name_length = SwapWord((BYTE*)d, sizeof(WORD));
d += sizeof(WORD);
if (TNEF->Debug >= 1)
printf("Sent For : %s", d);
d += name_length;
SIZECHECK(sizeof(WORD));
addr_length = SwapWord((BYTE*)d, sizeof(WORD));
d += sizeof(WORD);
if (TNEF->Debug >= 1)
printf("<%s>\n", d);
d += addr_length;
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFDateHandler STD_ARGLIST {
dtr *Date;
Attachment *p;
WORD * tmp_src, *tmp_dst;
int i;
p = &(TNEF->starting_attach);
switch (TNEFList[id].id) {
case attDateSent: Date = &(TNEF->dateSent); break;
case attDateRecd: Date = &(TNEF->dateReceived); break;
case attDateModified: Date = &(TNEF->dateModified); break;
case attDateStart: Date = &(TNEF->DateStart); break;
case attDateEnd: Date = &(TNEF->DateEnd); break;
case attAttachCreateDate:
while (p->next != NULL) p = p->next;
Date = &(p->CreateDate);
break;
case attAttachModifyDate:
while (p->next != NULL) p = p->next;
Date = &(p->ModifyDate);
break;
default:
if (TNEF->Debug >= 1)
printf("MISSING CASE\n");
return YTNEF_UNKNOWN_PROPERTY;
}
tmp_src = (WORD *)data;
tmp_dst = (WORD *)Date;
for (i = 0; i < sizeof(dtr) / sizeof(WORD); i++) {
*tmp_dst++ = SwapWord((BYTE *)tmp_src++, sizeof(WORD));
}
return 0;
}
void TNEFPrintDate(dtr Date) {
char days[7][15] = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
};
char months[12][15] = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"
};
if (Date.wDayOfWeek < 7)
printf("%s ", days[Date.wDayOfWeek]);
if ((Date.wMonth < 13) && (Date.wMonth > 0))
printf("%s ", months[Date.wMonth - 1]);
printf("%hu, %hu ", Date.wDay, Date.wYear);
if (Date.wHour > 12)
printf("%i:%02hu:%02hu pm", (Date.wHour - 12),
Date.wMinute, Date.wSecond);
else if (Date.wHour == 12)
printf("%hu:%02hu:%02hu pm", (Date.wHour),
Date.wMinute, Date.wSecond);
else
printf("%hu:%02hu:%02hu am", Date.wHour,
Date.wMinute, Date.wSecond);
}
// -----------------------------------------------------------------------------
int TNEFHexBreakdown STD_ARGLIST {
int i;
if (TNEF->Debug == 0)
return 0;
printf("%s: [%i bytes] \n", TNEFList[id].name, size);
for (i = 0; i < size; i++) {
printf("%02x ", data[i]);
if ((i + 1) % 16 == 0) printf("\n");
}
printf("\n");
return 0;
}
// -----------------------------------------------------------------------------
int TNEFDetailedPrint STD_ARGLIST {
int i;
if (TNEF->Debug == 0)
return 0;
printf("%s: [%i bytes] \n", TNEFList[id].name, size);
for (i = 0; i < size; i++) {
printf("%c", data[i]);
}
printf("\n");
return 0;
}
// -----------------------------------------------------------------------------
int TNEFAttachmentFilename STD_ARGLIST {
Attachment *p;
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
p->Title.size = size;
p->Title.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(p->Title.data);
memcpy(p->Title.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFAttachmentSave STD_ARGLIST {
Attachment *p;
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
p->FileData.data = calloc(sizeof(char), size);
ALLOCCHECK(p->FileData.data);
p->FileData.size = size;
memcpy(p->FileData.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFPriority STD_ARGLIST {
DWORD value;
value = SwapDWord((BYTE*)data, size);
switch (value) {
case 3:
sprintf((TNEF->priority), "high");
break;
case 2:
sprintf((TNEF->priority), "normal");
break;
case 1:
sprintf((TNEF->priority), "low");
break;
default:
sprintf((TNEF->priority), "N/A");
break;
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFCheckForSignature(DWORD sig) {
DWORD signature = 0x223E9F78;
sig = SwapDWord((BYTE *)&sig, sizeof(DWORD));
if (signature == sig) {
return 0;
} else {
return YTNEF_NOT_TNEF_STREAM;
}
}
// -----------------------------------------------------------------------------
int TNEFGetKey(TNEFStruct *TNEF, WORD *key) {
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(WORD), 1, key) < 1) {
if (TNEF->Debug >= 1)
printf("Error reading Key\n");
return YTNEF_ERROR_READING_DATA;
}
*key = SwapWord((BYTE *)key, sizeof(WORD));
DEBUG1(TNEF->Debug, 2, "Key = 0x%X", *key);
DEBUG1(TNEF->Debug, 2, "Key = %i", *key);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFGetHeader(TNEFStruct *TNEF, DWORD *type, DWORD *size) {
BYTE component;
DEBUG(TNEF->Debug, 2, "About to read Component");
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(BYTE), 1, &component) < 1) {
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "About to read type");
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, type) < 1) {
if (TNEF->Debug >= 1)
printf("ERROR: Error reading type\n");
return YTNEF_ERROR_READING_DATA;
}
DEBUG1(TNEF->Debug, 2, "Type = 0x%X", *type);
DEBUG1(TNEF->Debug, 2, "Type = %u", *type);
DEBUG(TNEF->Debug, 2, "About to read size");
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, size) < 1) {
if (TNEF->Debug >= 1)
printf("ERROR: Error reading size\n");
return YTNEF_ERROR_READING_DATA;
}
DEBUG1(TNEF->Debug, 2, "Size = %u", *size);
*type = SwapDWord((BYTE *)type, sizeof(DWORD));
*size = SwapDWord((BYTE *)size, sizeof(DWORD));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFRawRead(TNEFStruct *TNEF, BYTE *data, DWORD size, WORD *checksum) {
WORD temp;
int i;
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(BYTE), size, data) < size) {
if (TNEF->Debug >= 1)
printf("ERROR: Error reading data\n");
return YTNEF_ERROR_READING_DATA;
}
if (checksum != NULL) {
*checksum = 0;
for (i = 0; i < size; i++) {
temp = data[i];
*checksum = (*checksum + temp);
}
}
return 0;
}
#define INITVARLENGTH(x) (x).data = NULL; (x).size = 0;
#define INITDTR(x) (x).wYear=0; (x).wMonth=0; (x).wDay=0; \
(x).wHour=0; (x).wMinute=0; (x).wSecond=0; \
(x).wDayOfWeek=0;
#define INITSTR(x) memset((x), 0, sizeof(x));
void TNEFInitMapi(MAPIProps *p) {
p->count = 0;
p->properties = NULL;
}
void TNEFInitAttachment(Attachment *p) {
INITDTR(p->Date);
INITVARLENGTH(p->Title);
INITVARLENGTH(p->MetaFile);
INITDTR(p->CreateDate);
INITDTR(p->ModifyDate);
INITVARLENGTH(p->TransportFilename);
INITVARLENGTH(p->FileData);
INITVARLENGTH(p->IconData);
memset(&(p->RenderData), 0, sizeof(renddata));
TNEFInitMapi(&(p->MAPI));
p->next = NULL;
}
void TNEFInitialize(TNEFStruct *TNEF) {
INITSTR(TNEF->version);
INITVARLENGTH(TNEF->from);
INITVARLENGTH(TNEF->subject);
INITDTR(TNEF->dateSent);
INITDTR(TNEF->dateReceived);
INITSTR(TNEF->messageStatus);
INITSTR(TNEF->messageClass);
INITSTR(TNEF->messageID);
INITSTR(TNEF->parentID);
INITSTR(TNEF->conversationID);
INITVARLENGTH(TNEF->body);
INITSTR(TNEF->priority);
TNEFInitAttachment(&(TNEF->starting_attach));
INITDTR(TNEF->dateModified);
TNEFInitMapi(&(TNEF->MapiProperties));
INITVARLENGTH(TNEF->CodePage);
INITVARLENGTH(TNEF->OriginalMessageClass);
INITVARLENGTH(TNEF->Owner);
INITVARLENGTH(TNEF->SentFor);
INITVARLENGTH(TNEF->Delegate);
INITDTR(TNEF->DateStart);
INITDTR(TNEF->DateEnd);
INITVARLENGTH(TNEF->AidOwner);
TNEF->RequestRes = 0;
TNEF->IO.data = NULL;
TNEF->IO.InitProc = NULL;
TNEF->IO.ReadProc = NULL;
TNEF->IO.CloseProc = NULL;
}
#undef INITVARLENGTH
#undef INITDTR
#undef INITSTR
#define FREEVARLENGTH(x) if ((x).size > 0) { \
free((x).data); (x).size =0; }
void TNEFFree(TNEFStruct *TNEF) {
Attachment *p, *store;
FREEVARLENGTH(TNEF->from);
FREEVARLENGTH(TNEF->subject);
FREEVARLENGTH(TNEF->body);
FREEVARLENGTH(TNEF->CodePage);
FREEVARLENGTH(TNEF->OriginalMessageClass);
FREEVARLENGTH(TNEF->Owner);
FREEVARLENGTH(TNEF->SentFor);
FREEVARLENGTH(TNEF->Delegate);
FREEVARLENGTH(TNEF->AidOwner);
TNEFFreeMapiProps(&(TNEF->MapiProperties));
p = TNEF->starting_attach.next;
while (p != NULL) {
TNEFFreeAttachment(p);
store = p->next;
free(p);
p = store;
}
}
void TNEFFreeAttachment(Attachment *p) {
FREEVARLENGTH(p->Title);
FREEVARLENGTH(p->MetaFile);
FREEVARLENGTH(p->TransportFilename);
FREEVARLENGTH(p->FileData);
FREEVARLENGTH(p->IconData);
TNEFFreeMapiProps(&(p->MAPI));
}
void TNEFFreeMapiProps(MAPIProps *p) {
int i, j;
for (i = 0; i < p->count; i++) {
for (j = 0; j < p->properties[i].count; j++) {
FREEVARLENGTH(p->properties[i].data[j]);
}
free(p->properties[i].data);
for (j = 0; j < p->properties[i].namedproperty; j++) {
FREEVARLENGTH(p->properties[i].propnames[j]);
}
free(p->properties[i].propnames);
}
free(p->properties);
p->count = 0;
}
#undef FREEVARLENGTH
// Procedures to handle File IO
int TNEFFile_Open(TNEFIOStruct *IO) {
TNEFFileInfo *finfo;
finfo = (TNEFFileInfo *)IO->data;
DEBUG1(finfo->Debug, 3, "Opening %s", finfo->filename);
if ((finfo->fptr = fopen(finfo->filename, "rb")) == NULL) {
return -1;
} else {
return 0;
}
}
int TNEFFile_Read(TNEFIOStruct *IO, int size, int count, void *dest) {
TNEFFileInfo *finfo;
finfo = (TNEFFileInfo *)IO->data;
DEBUG2(finfo->Debug, 3, "Reading %i blocks of %i size", count, size);
if (finfo->fptr != NULL) {
return fread((BYTE *)dest, size, count, finfo->fptr);
} else {
return -1;
}
}
int TNEFFile_Close(TNEFIOStruct *IO) {
TNEFFileInfo *finfo;
finfo = (TNEFFileInfo *)IO->data;
DEBUG1(finfo->Debug, 3, "Closing file %s", finfo->filename);
if (finfo->fptr != NULL) {
fclose(finfo->fptr);
finfo->fptr = NULL;
}
return 0;
}
int TNEFParseFile(char *filename, TNEFStruct *TNEF) {
TNEFFileInfo finfo;
if (TNEF->Debug >= 1)
printf("Attempting to parse %s...\n", filename);
finfo.filename = filename;
finfo.fptr = NULL;
finfo.Debug = TNEF->Debug;
TNEF->IO.data = (void *)&finfo;
TNEF->IO.InitProc = TNEFFile_Open;
TNEF->IO.ReadProc = TNEFFile_Read;
TNEF->IO.CloseProc = TNEFFile_Close;
return TNEFParse(TNEF);
}
//-------------------------------------------------------------
// Procedures to handle Memory IO
int TNEFMemory_Open(TNEFIOStruct *IO) {
TNEFMemInfo *minfo;
minfo = (TNEFMemInfo *)IO->data;
minfo->ptr = minfo->dataStart;
return 0;
}
int TNEFMemory_Read(TNEFIOStruct *IO, int size, int count, void *dest) {
TNEFMemInfo *minfo;
int length;
long max;
minfo = (TNEFMemInfo *)IO->data;
length = count * size;
max = (minfo->dataStart + minfo->size) - (minfo->ptr);
if (length > max) {
return -1;
}
DEBUG1(minfo->Debug, 3, "Copying %i bytes", length);
memcpy(dest, minfo->ptr, length);
minfo->ptr += length;
return count;
}
int TNEFMemory_Close(TNEFIOStruct *IO) {
// Do nothing, really...
return 0;
}
int TNEFParseMemory(BYTE *memory, long size, TNEFStruct *TNEF) {
TNEFMemInfo minfo;
DEBUG(TNEF->Debug, 1, "Attempting to parse memory block...\n");
minfo.dataStart = memory;
minfo.ptr = memory;
minfo.size = size;
minfo.Debug = TNEF->Debug;
TNEF->IO.data = (void *)&minfo;
TNEF->IO.InitProc = TNEFMemory_Open;
TNEF->IO.ReadProc = TNEFMemory_Read;
TNEF->IO.CloseProc = TNEFMemory_Close;
return TNEFParse(TNEF);
}
int TNEFParse(TNEFStruct *TNEF) {
WORD key;
DWORD type;
DWORD size;
DWORD signature;
BYTE *data;
WORD checksum, header_checksum;
int i;
if (TNEF->IO.ReadProc == NULL) {
printf("ERROR: Setup incorrectly: No ReadProc\n");
return YTNEF_INCORRECT_SETUP;
}
if (TNEF->IO.InitProc != NULL) {
DEBUG(TNEF->Debug, 2, "About to initialize");
if (TNEF->IO.InitProc(&TNEF->IO) != 0) {
return YTNEF_CANNOT_INIT_DATA;
}
DEBUG(TNEF->Debug, 2, "Initialization finished");
}
DEBUG(TNEF->Debug, 2, "Reading Signature");
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {
printf("ERROR: Error reading signature\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "Checking Signature");
if (TNEFCheckForSignature(signature) < 0) {
printf("ERROR: Signature does not match. Not TNEF.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NOT_TNEF_STREAM;
}
DEBUG(TNEF->Debug, 2, "Reading Key.");
if (TNEFGetKey(TNEF, &key) < 0) {
printf("ERROR: Unable to retrieve key.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NO_KEY;
}
DEBUG(TNEF->Debug, 2, "Starting Full Processing.");
while (TNEFGetHeader(TNEF, &type, &size) == 0) {
DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size);
DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size);
if(size == 0) {
printf("ERROR: Field with size of 0\n");
return YTNEF_ERROR_READING_DATA;
}
data = calloc(size, sizeof(BYTE));
ALLOCCHECK(data);
if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {
printf("ERROR: Unable to read data.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {
printf("ERROR: Unable to read checksum.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));
if (checksum != header_checksum) {
printf("ERROR: Checksum mismatch. Data corruption?:\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_BAD_CHECKSUM;
}
for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {
if (TNEFList[i].id == type) {
if (TNEFList[i].handler != NULL) {
if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {
free(data);
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_IN_HANDLER;
} else {
// Found our handler and processed it. now time to get out
break;
}
} else {
DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes",
TNEFList[i].name, size);
}
}
}
free(data);
}
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return 0;
}
// ----------------------------------------------------------------------------
variableLength *MAPIFindUserProp(MAPIProps *p, unsigned int ID) {
int i;
if (p != NULL) {
for (i = 0; i < p->count; i++) {
if ((p->properties[i].id == ID) && (p->properties[i].custom == 1)) {
return (p->properties[i].data);
}
}
}
return MAPI_UNDEFINED;
}
variableLength *MAPIFindProperty(MAPIProps *p, unsigned int ID) {
int i;
if (p != NULL) {
for (i = 0; i < p->count; i++) {
if ((p->properties[i].id == ID) && (p->properties[i].custom == 0)) {
return (p->properties[i].data);
}
}
}
return MAPI_UNDEFINED;
}
int MAPISysTimetoDTR(BYTE *data, dtr *thedate) {
DDWORD ddword_tmp;
int startingdate = 0;
int tmp_date;
int days_in_year = 365;
unsigned int months[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
ddword_tmp = *((DDWORD *)data);
ddword_tmp = ddword_tmp / 10; // micro-s
ddword_tmp /= 1000; // ms
ddword_tmp /= 1000; // s
thedate->wSecond = (ddword_tmp % 60);
ddword_tmp /= 60; // seconds to minutes
thedate->wMinute = (ddword_tmp % 60);
ddword_tmp /= 60; //minutes to hours
thedate->wHour = (ddword_tmp % 24);
ddword_tmp /= 24; // Hours to days
// Now calculate the year based on # of days
thedate->wYear = 1601;
startingdate = 1;
while (ddword_tmp >= days_in_year) {
ddword_tmp -= days_in_year;
thedate->wYear++;
days_in_year = 365;
startingdate++;
if ((thedate->wYear % 4) == 0) {
if ((thedate->wYear % 100) == 0) {
// if the year is 1700,1800,1900, etc, then it is only
// a leap year if exactly divisible by 400, not 4.
if ((thedate->wYear % 400) == 0) {
startingdate++;
days_in_year = 366;
}
} else {
startingdate++;
days_in_year = 366;
}
}
startingdate %= 7;
}
// the remaining number is the day # in this year
// So now calculate the Month, & Day of month
if ((thedate->wYear % 4) == 0) {
// 29 days in february in a leap year
months[1] = 29;
}
tmp_date = (int)ddword_tmp;
thedate->wDayOfWeek = (tmp_date + startingdate) % 7;
thedate->wMonth = 0;
while (tmp_date > months[thedate->wMonth]) {
tmp_date -= months[thedate->wMonth];
thedate->wMonth++;
}
thedate->wMonth++;
thedate->wDay = tmp_date + 1;
return 0;
}
void MAPIPrint(MAPIProps *p) {
int j, i, index, h, x;
DDWORD *ddword_ptr;
DDWORD ddword_tmp;
dtr thedate;
MAPIProperty *mapi;
variableLength *mapidata;
variableLength vlTemp;
int found;
for (j = 0; j < p->count; j++) {
mapi = &(p->properties[j]);
printf(" #%i: Type: [", j);
switch (PROP_TYPE(mapi->id)) {
case PT_UNSPECIFIED:
printf(" NONE "); break;
case PT_NULL:
printf(" NULL "); break;
case PT_I2:
printf(" I2 "); break;
case PT_LONG:
printf(" LONG "); break;
case PT_R4:
printf(" R4 "); break;
case PT_DOUBLE:
printf(" DOUBLE "); break;
case PT_CURRENCY:
printf("CURRENCY "); break;
case PT_APPTIME:
printf("APP TIME "); break;
case PT_ERROR:
printf(" ERROR "); break;
case PT_BOOLEAN:
printf(" BOOLEAN "); break;
case PT_OBJECT:
printf(" OBJECT "); break;
case PT_I8:
printf(" I8 "); break;
case PT_STRING8:
printf(" STRING8 "); break;
case PT_UNICODE:
printf(" UNICODE "); break;
case PT_SYSTIME:
printf("SYS TIME "); break;
case PT_CLSID:
printf("OLE GUID "); break;
case PT_BINARY:
printf(" BINARY "); break;
default:
printf("<%x>", PROP_TYPE(mapi->id)); break;
}
printf("] Code: [");
if (mapi->custom == 1) {
printf("UD:x%04x", PROP_ID(mapi->id));
} else {
found = 0;
for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) {
if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) {
printf("%s", MPList[index].name);
found = 1;
}
}
if (found == 0) {
printf("0x%04x", PROP_ID(mapi->id));
}
}
printf("]\n");
if (mapi->namedproperty > 0) {
for (i = 0; i < mapi->namedproperty; i++) {
printf(" Name: %s\n", mapi->propnames[i].data);
}
}
for (i = 0; i < mapi->count; i++) {
mapidata = &(mapi->data[i]);
if (mapi->count > 1) {
printf(" [%i/%u] ", i, mapi->count);
} else {
printf(" ");
}
printf("Size: %i", mapidata->size);
switch (PROP_TYPE(mapi->id)) {
case PT_SYSTIME:
MAPISysTimetoDTR(mapidata->data, &thedate);
printf(" Value: ");
ddword_tmp = *((DDWORD *)mapidata->data);
TNEFPrintDate(thedate);
printf(" [HEX: ");
for (x = 0; x < sizeof(ddword_tmp); x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("] (%llu)\n", ddword_tmp);
break;
case PT_LONG:
printf(" Value: %i\n", *((int*)mapidata->data));
break;
case PT_I2:
printf(" Value: %hi\n", *((short int*)mapidata->data));
break;
case PT_BOOLEAN:
if (mapi->data->data[0] != 0) {
printf(" Value: True\n");
} else {
printf(" Value: False\n");
}
break;
case PT_OBJECT:
printf("\n");
break;
case PT_BINARY:
if (IsCompressedRTF(mapidata) == 1) {
printf(" Detected Compressed RTF. ");
printf("Decompressed text follows\n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) {
printf("%s\n", vlTemp.data);
free(vlTemp.data);
}
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
} else {
printf(" Value: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_STRING8:
printf(" Value: [%s]\n", mapidata->data);
if (strlen((char*)mapidata->data) != mapidata->size - 1) {
printf("Detected Hidden data: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_CLSID:
printf(" Value: ");
printf("[HEX: ");
for(x=0; x< 16; x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("]\n");
break;
default:
printf(" Value: [%s]\n", mapidata->data);
}
}
}
}
int IsCompressedRTF(variableLength *p) {
unsigned int in;
BYTE *src;
ULONG magic;
if (p->size < 4)
return 0;
src = p->data;
in = 0;
in += 4;
in += 4;
magic = SwapDWord((BYTE*)src + in, 4);
if (magic == 0x414c454d) {
return 1;
} else if (magic == 0x75465a4c) {
return 1;
} else {
return 0;
}
}
BYTE *DecompressRTF(variableLength *p, int *size) {
BYTE *dst; // destination for uncompressed bytes
BYTE *src;
unsigned int in;
unsigned int out;
variableLength comp_Prebuf;
ULONG compressedSize, uncompressedSize, magic;
comp_Prebuf.size = strlen(RTF_PREBUF);
comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1);
ALLOCCHECK_CHAR(comp_Prebuf.data);
memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size);
src = p->data;
in = 0;
if (p->size < 20) {
printf("File too small\n");
return(NULL);
}
compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
magic = SwapDWord((BYTE*)src + in, 4);
in += 4;
in += 4;
// check size excluding the size field itself
if (compressedSize != p->size - 4) {
printf(" Size Mismatch: %u != %i\n", compressedSize, p->size - 4);
free(comp_Prebuf.data);
return NULL;
}
// process the data
if (magic == 0x414c454d) {
// magic number that identifies the stream as a uncompressed stream
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + 4, uncompressedSize);
} else if (magic == 0x75465a4c) {
// magic number that identifies the stream as a compressed stream
int flagCount = 0;
int flags = 0;
// Prevent overflow on 32 Bit Systems
if (comp_Prebuf.size >= INT_MAX - uncompressedSize) {
printf("Corrupted file\n");
exit(-1);
}
dst = calloc(comp_Prebuf.size + uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, comp_Prebuf.data, comp_Prebuf.size);
out = comp_Prebuf.size;
while (out < (comp_Prebuf.size + uncompressedSize)) {
// each flag byte flags 8 literals/references, 1 per bit
flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1;
if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal
unsigned int offset = src[in++];
unsigned int length = src[in++];
unsigned int end;
offset = (offset << 4) | (length >> 4); // the offset relative to block start
length = (length & 0xF) + 2; // the number of bytes to copy
// the decompression buffer is supposed to wrap around back
// to the beginning when the end is reached. we save the
// need for such a buffer by pointing straight into the data
// buffer, and simulating this behaviour by modifying the
// pointers appropriately.
offset = (out / 4096) * 4096 + offset;
if (offset >= out) // take from previous block
offset -= 4096;
// note: can't use System.arraycopy, because the referenced
// bytes can cross through the current out position.
end = offset + length;
while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize))
&& (offset < (comp_Prebuf.size + uncompressedSize)))
dst[out++] = dst[offset++];
} else { // literal
if ((out >= (comp_Prebuf.size + uncompressedSize)) ||
(in >= p->size)) {
printf("Corrupted stream\n");
exit(-1);
}
dst[out++] = src[in++];
}
}
// copy it back without the prebuffered data
src = dst;
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + comp_Prebuf.size, uncompressedSize);
free(src);
*size = uncompressedSize;
free(comp_Prebuf.data);
return dst;
} else { // unknown magic number
printf("Unknown compression type (magic number %x)\n", magic);
}
free(comp_Prebuf.data);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3208_0 |
crossvul-cpp_data_good_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 BOOL ntlm_av_pair_get_next_offset(const NTLM_AV_PAIR* pAvPair, size_t size, size_t* pOffset);
static BOOL ntlm_av_pair_check_data(const NTLM_AV_PAIR* pAvPair, size_t cbAvPair, size_t size)
{
size_t offset;
if (!pAvPair || cbAvPair < sizeof(NTLM_AV_PAIR) + size)
return FALSE;
if (!ntlm_av_pair_get_next_offset(pAvPair, cbAvPair, &offset))
return FALSE;
return cbAvPair >= offset;
}
static const char* get_av_pair_string(UINT16 pair)
{
switch (pair)
{
case MsvAvEOL:
return "MsvAvEOL";
case MsvAvNbComputerName:
return "MsvAvNbComputerName";
case MsvAvNbDomainName:
return "MsvAvNbDomainName";
case MsvAvDnsComputerName:
return "MsvAvDnsComputerName";
case MsvAvDnsDomainName:
return "MsvAvDnsDomainName";
case MsvAvDnsTreeName:
return "MsvAvDnsTreeName";
case MsvAvFlags:
return "MsvAvFlags";
case MsvAvTimestamp:
return "MsvAvTimestamp";
case MsvAvSingleHost:
return "MsvAvSingleHost";
case MsvAvTargetName:
return "MsvAvTargetName";
case MsvChannelBindings:
return "MsvChannelBindings";
default:
return "UNKNOWN";
}
}
static BOOL ntlm_av_pair_check(const 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 BOOL ntlm_av_pair_get_id(const NTLM_AV_PAIR* pAvPair, size_t size, UINT16* pair)
{
UINT16 AvId;
if (!pAvPair || !pair)
return FALSE;
if (size < sizeof(NTLM_AV_PAIR))
return FALSE;
Data_Read_UINT16(&pAvPair->AvId, AvId);
*pair = AvId;
return TRUE;
}
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 BOOL ntlm_av_pair_get_len(const NTLM_AV_PAIR* pAvPair, size_t size, size_t* pAvLen)
{
UINT16 AvLen;
if (!pAvPair)
return FALSE;
if (size < sizeof(NTLM_AV_PAIR))
return FALSE;
Data_Read_UINT16(&pAvPair->AvLen, AvLen);
*pAvLen = AvLen;
return TRUE;
}
void ntlm_print_av_pair_list(NTLM_AV_PAIR* pAvPairList, size_t cbAvPairList)
{
UINT16 pair;
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, cbAvPair, &pair) && (pair != MsvAvEOL))
{
size_t cbLen = 0;
ntlm_av_pair_get_len(pAvPair, cbAvPair, &cbLen);
WLog_INFO(TAG, "\t%s AvId: %" PRIu16 " AvLen: %" PRIu16 "", get_av_pair_string(pair), pair);
winpr_HexDump(TAG, WLOG_INFO, ntlm_av_pair_get_value_pointer(pAvPair), cbLen);
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 BOOL ntlm_av_pair_get_next_offset(const NTLM_AV_PAIR* pAvPair, size_t size, size_t* pOffset)
{
size_t avLen;
if (!pOffset)
return FALSE;
if (!ntlm_av_pair_get_len(pAvPair, size, &avLen))
return FALSE;
*pOffset = avLen + sizeof(NTLM_AV_PAIR);
return TRUE;
}
static BOOL ntlm_av_pair_check(const NTLM_AV_PAIR* pAvPair, size_t cbAvPair)
{
return ntlm_av_pair_check_data(pAvPair, cbAvPair, 0);
}
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;
if (!ntlm_av_pair_get_next_offset(pAvPair, *pcbAvPair, &offset))
return NULL;
*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)
{
UINT16 id;
size_t cbAvPair = cbAvPairList;
NTLM_AV_PAIR* pAvPair = pAvPairList;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
pAvPair = NULL;
while (pAvPair && ntlm_av_pair_get_id(pAvPair, cbAvPair, &id))
{
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)
{
UINT16 pair;
size_t avLen;
if (!ntlm_av_pair_check(pAvPair, cbAvPair))
return FALSE;
if (!ntlm_av_pair_get_id(pAvPair, cbAvPair, &pair))
return FALSE;
if (!ntlm_av_pair_get_len(pAvPair, cbAvPair, &avLen))
return FALSE;
return ntlm_av_pair_add(pAvPairList, cbAvPairList, pair,
ntlm_av_pair_get_value_pointer(pAvPair), avLen);
}
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)
{
size_t avLen;
if (!ntlm_av_pair_get_len(AvNbDomainName, cbAvNbDomainName, &avLen))
goto fail;
AvPairsCount++; /* MsvAvNbDomainName */
AvPairsValueLength += avLen;
}
if (AvNbComputerName)
{
size_t avLen;
if (!ntlm_av_pair_get_len(AvNbComputerName, cbAvNbComputerName, &avLen))
goto fail;
AvPairsCount++; /* MsvAvNbComputerName */
AvPairsValueLength += avLen;
}
if (AvDnsDomainName)
{
size_t avLen;
if (!ntlm_av_pair_get_len(AvDnsDomainName, cbAvDnsDomainName, &avLen))
goto fail;
AvPairsCount++; /* MsvAvDnsDomainName */
AvPairsValueLength += avLen;
}
if (AvDnsComputerName)
{
size_t avLen;
if (!ntlm_av_pair_get_len(AvDnsComputerName, cbAvDnsComputerName, &avLen))
goto fail;
AvPairsCount++; /* MsvAvDnsComputerName */
AvPairsValueLength += avLen;
}
if (AvDnsTreeName)
{
size_t avLen;
if (!ntlm_av_pair_get_len(AvDnsTreeName, cbAvDnsTreeName, &avLen))
goto fail;
AvPairsCount++; /* MsvAvDnsTreeName */
AvPairsValueLength += avLen;
}
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/good_3953_0 |
crossvul-cpp_data_bad_2916_0 | /*
* Released under the GPLv2 only.
* SPDX-License-Identifier: GPL-2.0
*/
#include <linux/usb.h>
#include <linux/usb/ch9.h>
#include <linux/usb/hcd.h>
#include <linux/usb/quirks.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <asm/byteorder.h>
#include "usb.h"
#define USB_MAXALTSETTING 128 /* Hard limit */
#define USB_MAXCONFIG 8 /* Arbitrary limit */
static inline const char *plural(int n)
{
return (n == 1 ? "" : "s");
}
static int find_next_descriptor(unsigned char *buffer, int size,
int dt1, int dt2, int *num_skipped)
{
struct usb_descriptor_header *h;
int n = 0;
unsigned char *buffer0 = buffer;
/* Find the next descriptor of type dt1 or dt2 */
while (size > 0) {
h = (struct usb_descriptor_header *) buffer;
if (h->bDescriptorType == dt1 || h->bDescriptorType == dt2)
break;
buffer += h->bLength;
size -= h->bLength;
++n;
}
/* Store the number of descriptors skipped and return the
* number of bytes skipped */
if (num_skipped)
*num_skipped = n;
return buffer - buffer0;
}
static void usb_parse_ssp_isoc_endpoint_companion(struct device *ddev,
int cfgno, int inum, int asnum, struct usb_host_endpoint *ep,
unsigned char *buffer, int size)
{
struct usb_ssp_isoc_ep_comp_descriptor *desc;
/*
* The SuperSpeedPlus Isoc endpoint companion descriptor immediately
* follows the SuperSpeed Endpoint Companion descriptor
*/
desc = (struct usb_ssp_isoc_ep_comp_descriptor *) buffer;
if (desc->bDescriptorType != USB_DT_SSP_ISOC_ENDPOINT_COMP ||
size < USB_DT_SSP_ISOC_EP_COMP_SIZE) {
dev_warn(ddev, "Invalid SuperSpeedPlus isoc endpoint companion"
"for config %d interface %d altsetting %d ep %d.\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
return;
}
memcpy(&ep->ssp_isoc_ep_comp, desc, USB_DT_SSP_ISOC_EP_COMP_SIZE);
}
static void usb_parse_ss_endpoint_companion(struct device *ddev, int cfgno,
int inum, int asnum, struct usb_host_endpoint *ep,
unsigned char *buffer, int size)
{
struct usb_ss_ep_comp_descriptor *desc;
int max_tx;
/* The SuperSpeed endpoint companion descriptor is supposed to
* be the first thing immediately following the endpoint descriptor.
*/
desc = (struct usb_ss_ep_comp_descriptor *) buffer;
if (desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP ||
size < USB_DT_SS_EP_COMP_SIZE) {
dev_warn(ddev, "No SuperSpeed endpoint companion for config %d "
" interface %d altsetting %d ep %d: "
"using minimum values\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
/* Fill in some default values.
* Leave bmAttributes as zero, which will mean no streams for
* bulk, and isoc won't support multiple bursts of packets.
* With bursts of only one packet, and a Mult of 1, the max
* amount of data moved per endpoint service interval is one
* packet.
*/
ep->ss_ep_comp.bLength = USB_DT_SS_EP_COMP_SIZE;
ep->ss_ep_comp.bDescriptorType = USB_DT_SS_ENDPOINT_COMP;
if (usb_endpoint_xfer_isoc(&ep->desc) ||
usb_endpoint_xfer_int(&ep->desc))
ep->ss_ep_comp.wBytesPerInterval =
ep->desc.wMaxPacketSize;
return;
}
buffer += desc->bLength;
size -= desc->bLength;
memcpy(&ep->ss_ep_comp, desc, USB_DT_SS_EP_COMP_SIZE);
/* Check the various values */
if (usb_endpoint_xfer_control(&ep->desc) && desc->bMaxBurst != 0) {
dev_warn(ddev, "Control endpoint with bMaxBurst = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to zero\n", desc->bMaxBurst,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bMaxBurst = 0;
} else if (desc->bMaxBurst > 15) {
dev_warn(ddev, "Endpoint with bMaxBurst = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to 15\n", desc->bMaxBurst,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bMaxBurst = 15;
}
if ((usb_endpoint_xfer_control(&ep->desc) ||
usb_endpoint_xfer_int(&ep->desc)) &&
desc->bmAttributes != 0) {
dev_warn(ddev, "%s endpoint with bmAttributes = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to zero\n",
usb_endpoint_xfer_control(&ep->desc) ? "Control" : "Bulk",
desc->bmAttributes,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 0;
} else if (usb_endpoint_xfer_bulk(&ep->desc) &&
desc->bmAttributes > 16) {
dev_warn(ddev, "Bulk endpoint with more than 65536 streams in "
"config %d interface %d altsetting %d ep %d: "
"setting to max\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 16;
} else if (usb_endpoint_xfer_isoc(&ep->desc) &&
!USB_SS_SSP_ISOC_COMP(desc->bmAttributes) &&
USB_SS_MULT(desc->bmAttributes) > 3) {
dev_warn(ddev, "Isoc endpoint has Mult of %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to 3\n",
USB_SS_MULT(desc->bmAttributes),
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 2;
}
if (usb_endpoint_xfer_isoc(&ep->desc))
max_tx = (desc->bMaxBurst + 1) *
(USB_SS_MULT(desc->bmAttributes)) *
usb_endpoint_maxp(&ep->desc);
else if (usb_endpoint_xfer_int(&ep->desc))
max_tx = usb_endpoint_maxp(&ep->desc) *
(desc->bMaxBurst + 1);
else
max_tx = 999999;
if (le16_to_cpu(desc->wBytesPerInterval) > max_tx) {
dev_warn(ddev, "%s endpoint with wBytesPerInterval of %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to %d\n",
usb_endpoint_xfer_isoc(&ep->desc) ? "Isoc" : "Int",
le16_to_cpu(desc->wBytesPerInterval),
cfgno, inum, asnum, ep->desc.bEndpointAddress,
max_tx);
ep->ss_ep_comp.wBytesPerInterval = cpu_to_le16(max_tx);
}
/* Parse a possible SuperSpeedPlus isoc ep companion descriptor */
if (usb_endpoint_xfer_isoc(&ep->desc) &&
USB_SS_SSP_ISOC_COMP(desc->bmAttributes))
usb_parse_ssp_isoc_endpoint_companion(ddev, cfgno, inum, asnum,
ep, buffer, size);
}
static const unsigned short low_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 8,
[USB_ENDPOINT_XFER_ISOC] = 0,
[USB_ENDPOINT_XFER_BULK] = 0,
[USB_ENDPOINT_XFER_INT] = 8,
};
static const unsigned short full_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 64,
[USB_ENDPOINT_XFER_ISOC] = 1023,
[USB_ENDPOINT_XFER_BULK] = 64,
[USB_ENDPOINT_XFER_INT] = 64,
};
static const unsigned short high_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 64,
[USB_ENDPOINT_XFER_ISOC] = 1024,
[USB_ENDPOINT_XFER_BULK] = 512,
[USB_ENDPOINT_XFER_INT] = 1024,
};
static const unsigned short super_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 512,
[USB_ENDPOINT_XFER_ISOC] = 1024,
[USB_ENDPOINT_XFER_BULK] = 1024,
[USB_ENDPOINT_XFER_INT] = 1024,
};
static int usb_parse_endpoint(struct device *ddev, int cfgno, int inum,
int asnum, struct usb_host_interface *ifp, int num_ep,
unsigned char *buffer, int size)
{
unsigned char *buffer0 = buffer;
struct usb_endpoint_descriptor *d;
struct usb_host_endpoint *endpoint;
int n, i, j, retval;
unsigned int maxp;
const unsigned short *maxpacket_maxes;
d = (struct usb_endpoint_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
n = USB_DT_ENDPOINT_AUDIO_SIZE;
else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
n = USB_DT_ENDPOINT_SIZE;
else {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint descriptor of length %d, skipping\n",
cfgno, inum, asnum, d->bLength);
goto skip_to_next_endpoint_or_interface_descriptor;
}
i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
if (i >= 16 || i == 0) {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
/* Only store as many endpoints as we have room for */
if (ifp->desc.bNumEndpoints >= num_ep)
goto skip_to_next_endpoint_or_interface_descriptor;
/* Check for duplicate endpoint addresses */
for (i = 0; i < ifp->desc.bNumEndpoints; ++i) {
if (ifp->endpoint[i].desc.bEndpointAddress ==
d->bEndpointAddress) {
dev_warn(ddev, "config %d interface %d altsetting %d has a duplicate endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
}
endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
++ifp->desc.bNumEndpoints;
memcpy(&endpoint->desc, d, n);
INIT_LIST_HEAD(&endpoint->urb_list);
/*
* Fix up bInterval values outside the legal range.
* Use 10 or 8 ms if no proper value can be guessed.
*/
i = 0; /* i = min, j = max, n = default */
j = 255;
if (usb_endpoint_xfer_int(d)) {
i = 1;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_SUPER_PLUS:
case USB_SPEED_SUPER:
case USB_SPEED_HIGH:
/*
* Many device manufacturers are using full-speed
* bInterval values in high-speed interrupt endpoint
* descriptors. Try to fix those and fall back to an
* 8-ms default value otherwise.
*/
n = fls(d->bInterval*8);
if (n == 0)
n = 7; /* 8 ms = 2^(7-1) uframes */
j = 16;
/*
* Adjust bInterval for quirked devices.
*/
/*
* This quirk fixes bIntervals reported in ms.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval) + 3, i, j);
i = j = n;
}
/*
* This quirk fixes bIntervals reported in
* linear microframes.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval), i, j);
i = j = n;
}
break;
default: /* USB_SPEED_FULL or _LOW */
/*
* For low-speed, 10 ms is the official minimum.
* But some "overclocked" devices might want faster
* polling so we'll allow it.
*/
n = 10;
break;
}
} else if (usb_endpoint_xfer_isoc(d)) {
i = 1;
j = 16;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_HIGH:
n = 7; /* 8 ms = 2^(7-1) uframes */
break;
default: /* USB_SPEED_FULL */
n = 4; /* 8 ms = 2^(4-1) frames */
break;
}
}
if (d->bInterval < i || d->bInterval > j) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X has an invalid bInterval %d, "
"changing to %d\n",
cfgno, inum, asnum,
d->bEndpointAddress, d->bInterval, n);
endpoint->desc.bInterval = n;
}
/* Some buggy low-speed devices have Bulk endpoints, which is
* explicitly forbidden by the USB spec. In an attempt to make
* them usable, we will try treating them as Interrupt endpoints.
*/
if (to_usb_device(ddev)->speed == USB_SPEED_LOW &&
usb_endpoint_xfer_bulk(d)) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X is Bulk; changing to Interrupt\n",
cfgno, inum, asnum, d->bEndpointAddress);
endpoint->desc.bmAttributes = USB_ENDPOINT_XFER_INT;
endpoint->desc.bInterval = 1;
if (usb_endpoint_maxp(&endpoint->desc) > 8)
endpoint->desc.wMaxPacketSize = cpu_to_le16(8);
}
/* Validate the wMaxPacketSize field */
maxp = usb_endpoint_maxp(&endpoint->desc);
/* Find the highest legal maxpacket size for this endpoint */
i = 0; /* additional transactions per microframe */
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_LOW:
maxpacket_maxes = low_speed_maxpacket_maxes;
break;
case USB_SPEED_FULL:
maxpacket_maxes = full_speed_maxpacket_maxes;
break;
case USB_SPEED_HIGH:
/* Bits 12..11 are allowed only for HS periodic endpoints */
if (usb_endpoint_xfer_int(d) || usb_endpoint_xfer_isoc(d)) {
i = maxp & (BIT(12) | BIT(11));
maxp &= ~i;
}
/* fallthrough */
default:
maxpacket_maxes = high_speed_maxpacket_maxes;
break;
case USB_SPEED_SUPER:
case USB_SPEED_SUPER_PLUS:
maxpacket_maxes = super_speed_maxpacket_maxes;
break;
}
j = maxpacket_maxes[usb_endpoint_type(&endpoint->desc)];
if (maxp > j) {
dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid maxpacket %d, setting to %d\n",
cfgno, inum, asnum, d->bEndpointAddress, maxp, j);
maxp = j;
endpoint->desc.wMaxPacketSize = cpu_to_le16(i | maxp);
}
/*
* Some buggy high speed devices have bulk endpoints using
* maxpacket sizes other than 512. High speed HCDs may not
* be able to handle that particular bug, so let's warn...
*/
if (to_usb_device(ddev)->speed == USB_SPEED_HIGH
&& usb_endpoint_xfer_bulk(d)) {
if (maxp != 512)
dev_warn(ddev, "config %d interface %d altsetting %d "
"bulk endpoint 0x%X has invalid maxpacket %d\n",
cfgno, inum, asnum, d->bEndpointAddress,
maxp);
}
/* Parse a possible SuperSpeed endpoint companion descriptor */
if (to_usb_device(ddev)->speed >= USB_SPEED_SUPER)
usb_parse_ss_endpoint_companion(ddev, cfgno,
inum, asnum, endpoint, buffer, size);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the next endpoint or interface descriptor */
endpoint->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
endpoint->extralen = i;
retval = buffer - buffer0 + i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "endpoint");
return retval;
skip_to_next_endpoint_or_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
void usb_release_interface_cache(struct kref *ref)
{
struct usb_interface_cache *intfc = ref_to_usb_interface_cache(ref);
int j;
for (j = 0; j < intfc->num_altsetting; j++) {
struct usb_host_interface *alt = &intfc->altsetting[j];
kfree(alt->endpoint);
kfree(alt->string);
}
kfree(intfc);
}
static int usb_parse_interface(struct device *ddev, int cfgno,
struct usb_host_config *config, unsigned char *buffer, int size,
u8 inums[], u8 nalts[])
{
unsigned char *buffer0 = buffer;
struct usb_interface_descriptor *d;
int inum, asnum;
struct usb_interface_cache *intfc;
struct usb_host_interface *alt;
int i, n;
int len, retval;
int num_ep, num_ep_orig;
d = (struct usb_interface_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength < USB_DT_INTERFACE_SIZE)
goto skip_to_next_interface_descriptor;
/* Which interface entry is this? */
intfc = NULL;
inum = d->bInterfaceNumber;
for (i = 0; i < config->desc.bNumInterfaces; ++i) {
if (inums[i] == inum) {
intfc = config->intf_cache[i];
break;
}
}
if (!intfc || intfc->num_altsetting >= nalts[i])
goto skip_to_next_interface_descriptor;
/* Check for duplicate altsetting entries */
asnum = d->bAlternateSetting;
for ((i = 0, alt = &intfc->altsetting[0]);
i < intfc->num_altsetting;
(++i, ++alt)) {
if (alt->desc.bAlternateSetting == asnum) {
dev_warn(ddev, "Duplicate descriptor for config %d "
"interface %d altsetting %d, skipping\n",
cfgno, inum, asnum);
goto skip_to_next_interface_descriptor;
}
}
++intfc->num_altsetting;
memcpy(&alt->desc, d, USB_DT_INTERFACE_SIZE);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first endpoint or interface descriptor */
alt->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
alt->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "interface");
buffer += i;
size -= i;
/* Allocate space for the right(?) number of endpoints */
num_ep = num_ep_orig = alt->desc.bNumEndpoints;
alt->desc.bNumEndpoints = 0; /* Use as a counter */
if (num_ep > USB_MAXENDPOINTS) {
dev_warn(ddev, "too many endpoints for config %d interface %d "
"altsetting %d: %d, using maximum allowed: %d\n",
cfgno, inum, asnum, num_ep, USB_MAXENDPOINTS);
num_ep = USB_MAXENDPOINTS;
}
if (num_ep > 0) {
/* Can't allocate 0 bytes */
len = sizeof(struct usb_host_endpoint) * num_ep;
alt->endpoint = kzalloc(len, GFP_KERNEL);
if (!alt->endpoint)
return -ENOMEM;
}
/* Parse all the endpoint descriptors */
n = 0;
while (size > 0) {
if (((struct usb_descriptor_header *) buffer)->bDescriptorType
== USB_DT_INTERFACE)
break;
retval = usb_parse_endpoint(ddev, cfgno, inum, asnum, alt,
num_ep, buffer, size);
if (retval < 0)
return retval;
++n;
buffer += retval;
size -= retval;
}
if (n != num_ep_orig)
dev_warn(ddev, "config %d interface %d altsetting %d has %d "
"endpoint descriptor%s, different from the interface "
"descriptor's value: %d\n",
cfgno, inum, asnum, n, plural(n), num_ep_orig);
return buffer - buffer0;
skip_to_next_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
static int usb_parse_configuration(struct usb_device *dev, int cfgidx,
struct usb_host_config *config, unsigned char *buffer, int size)
{
struct device *ddev = &dev->dev;
unsigned char *buffer0 = buffer;
int cfgno;
int nintf, nintf_orig;
int i, j, n;
struct usb_interface_cache *intfc;
unsigned char *buffer2;
int size2;
struct usb_descriptor_header *header;
int len, retval;
u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
unsigned iad_num = 0;
memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
if (config->desc.bDescriptorType != USB_DT_CONFIG ||
config->desc.bLength < USB_DT_CONFIG_SIZE ||
config->desc.bLength > size) {
dev_err(ddev, "invalid descriptor for config index %d: "
"type = 0x%X, length = %d\n", cfgidx,
config->desc.bDescriptorType, config->desc.bLength);
return -EINVAL;
}
cfgno = config->desc.bConfigurationValue;
buffer += config->desc.bLength;
size -= config->desc.bLength;
nintf = nintf_orig = config->desc.bNumInterfaces;
if (nintf > USB_MAXINTERFACES) {
dev_warn(ddev, "config %d has too many interfaces: %d, "
"using maximum allowed: %d\n",
cfgno, nintf, USB_MAXINTERFACES);
nintf = USB_MAXINTERFACES;
}
/* Go through the descriptors, checking their length and counting the
* number of altsettings for each interface */
n = 0;
for ((buffer2 = buffer, size2 = size);
size2 > 0;
(buffer2 += header->bLength, size2 -= header->bLength)) {
if (size2 < sizeof(struct usb_descriptor_header)) {
dev_warn(ddev, "config %d descriptor has %d excess "
"byte%s, ignoring\n",
cfgno, size2, plural(size2));
break;
}
header = (struct usb_descriptor_header *) buffer2;
if ((header->bLength > size2) || (header->bLength < 2)) {
dev_warn(ddev, "config %d has an invalid descriptor "
"of length %d, skipping remainder of the config\n",
cfgno, header->bLength);
break;
}
if (header->bDescriptorType == USB_DT_INTERFACE) {
struct usb_interface_descriptor *d;
int inum;
d = (struct usb_interface_descriptor *) header;
if (d->bLength < USB_DT_INTERFACE_SIZE) {
dev_warn(ddev, "config %d has an invalid "
"interface descriptor of length %d, "
"skipping\n", cfgno, d->bLength);
continue;
}
inum = d->bInterfaceNumber;
if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&
n >= nintf_orig) {
dev_warn(ddev, "config %d has more interface "
"descriptors, than it declares in "
"bNumInterfaces, ignoring interface "
"number: %d\n", cfgno, inum);
continue;
}
if (inum >= nintf_orig)
dev_warn(ddev, "config %d has an invalid "
"interface number: %d but max is %d\n",
cfgno, inum, nintf_orig - 1);
/* Have we already encountered this interface?
* Count its altsettings */
for (i = 0; i < n; ++i) {
if (inums[i] == inum)
break;
}
if (i < n) {
if (nalts[i] < 255)
++nalts[i];
} else if (n < USB_MAXINTERFACES) {
inums[n] = inum;
nalts[n] = 1;
++n;
}
} else if (header->bDescriptorType ==
USB_DT_INTERFACE_ASSOCIATION) {
struct usb_interface_assoc_descriptor *d;
d = (struct usb_interface_assoc_descriptor *)header;
if (d->bLength < USB_DT_INTERFACE_ASSOCIATION_SIZE) {
dev_warn(ddev,
"config %d has an invalid interface association descriptor of length %d, skipping\n",
cfgno, d->bLength);
continue;
}
if (iad_num == USB_MAXIADS) {
dev_warn(ddev, "found more Interface "
"Association Descriptors "
"than allocated for in "
"configuration %d\n", cfgno);
} else {
config->intf_assoc[iad_num] = d;
iad_num++;
}
} else if (header->bDescriptorType == USB_DT_DEVICE ||
header->bDescriptorType == USB_DT_CONFIG)
dev_warn(ddev, "config %d contains an unexpected "
"descriptor of type 0x%X, skipping\n",
cfgno, header->bDescriptorType);
} /* for ((buffer2 = buffer, size2 = size); ...) */
size = buffer2 - buffer;
config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
if (n != nintf)
dev_warn(ddev, "config %d has %d interface%s, different from "
"the descriptor's value: %d\n",
cfgno, n, plural(n), nintf_orig);
else if (n == 0)
dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
config->desc.bNumInterfaces = nintf = n;
/* Check for missing interface numbers */
for (i = 0; i < nintf; ++i) {
for (j = 0; j < nintf; ++j) {
if (inums[j] == i)
break;
}
if (j >= nintf)
dev_warn(ddev, "config %d has no interface number "
"%d\n", cfgno, i);
}
/* Allocate the usb_interface_caches and altsetting arrays */
for (i = 0; i < nintf; ++i) {
j = nalts[i];
if (j > USB_MAXALTSETTING) {
dev_warn(ddev, "too many alternate settings for "
"config %d interface %d: %d, "
"using maximum allowed: %d\n",
cfgno, inums[i], j, USB_MAXALTSETTING);
nalts[i] = j = USB_MAXALTSETTING;
}
len = sizeof(*intfc) + sizeof(struct usb_host_interface) * j;
config->intf_cache[i] = intfc = kzalloc(len, GFP_KERNEL);
if (!intfc)
return -ENOMEM;
kref_init(&intfc->ref);
}
/* FIXME: parse the BOS descriptor */
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first interface descriptor */
config->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, &n);
config->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "configuration");
buffer += i;
size -= i;
/* Parse all the interface/altsetting descriptors */
while (size > 0) {
retval = usb_parse_interface(ddev, cfgno, config,
buffer, size, inums, nalts);
if (retval < 0)
return retval;
buffer += retval;
size -= retval;
}
/* Check for missing altsettings */
for (i = 0; i < nintf; ++i) {
intfc = config->intf_cache[i];
for (j = 0; j < intfc->num_altsetting; ++j) {
for (n = 0; n < intfc->num_altsetting; ++n) {
if (intfc->altsetting[n].desc.
bAlternateSetting == j)
break;
}
if (n >= intfc->num_altsetting)
dev_warn(ddev, "config %d interface %d has no "
"altsetting %d\n", cfgno, inums[i], j);
}
}
return 0;
}
/* hub-only!! ... and only exported for reset/reinit path.
* otherwise used internally on disconnect/destroy path
*/
void usb_destroy_configuration(struct usb_device *dev)
{
int c, i;
if (!dev->config)
return;
if (dev->rawdescriptors) {
for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
kfree(dev->rawdescriptors[i]);
kfree(dev->rawdescriptors);
dev->rawdescriptors = NULL;
}
for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
struct usb_host_config *cf = &dev->config[c];
kfree(cf->string);
for (i = 0; i < cf->desc.bNumInterfaces; i++) {
if (cf->intf_cache[i])
kref_put(&cf->intf_cache[i]->ref,
usb_release_interface_cache);
}
}
kfree(dev->config);
dev->config = NULL;
}
/*
* Get the USB config descriptors, cache and parse'em
*
* hub-only!! ... and only in reset path, or usb_new_device()
* (used by real hubs and virtual root hubs)
*/
int usb_get_configuration(struct usb_device *dev)
{
struct device *ddev = &dev->dev;
int ncfg = dev->descriptor.bNumConfigurations;
int result = 0;
unsigned int cfgno, length;
unsigned char *bigbuffer;
struct usb_config_descriptor *desc;
cfgno = 0;
result = -ENOMEM;
if (ncfg > USB_MAXCONFIG) {
dev_warn(ddev, "too many configurations: %d, "
"using maximum allowed: %d\n", ncfg, USB_MAXCONFIG);
dev->descriptor.bNumConfigurations = ncfg = USB_MAXCONFIG;
}
if (ncfg < 1) {
dev_err(ddev, "no configurations\n");
return -EINVAL;
}
length = ncfg * sizeof(struct usb_host_config);
dev->config = kzalloc(length, GFP_KERNEL);
if (!dev->config)
goto err2;
length = ncfg * sizeof(char *);
dev->rawdescriptors = kzalloc(length, GFP_KERNEL);
if (!dev->rawdescriptors)
goto err2;
desc = kmalloc(USB_DT_CONFIG_SIZE, GFP_KERNEL);
if (!desc)
goto err2;
result = 0;
for (; cfgno < ncfg; cfgno++) {
/* We grab just the first descriptor so we know how long
* the whole configuration is */
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
desc, USB_DT_CONFIG_SIZE);
if (result < 0) {
dev_err(ddev, "unable to read config index %d "
"descriptor/%s: %d\n", cfgno, "start", result);
if (result != -EPIPE)
goto err;
dev_err(ddev, "chopping to %d config(s)\n", cfgno);
dev->descriptor.bNumConfigurations = cfgno;
break;
} else if (result < 4) {
dev_err(ddev, "config index %d descriptor too short "
"(expected %i, got %i)\n", cfgno,
USB_DT_CONFIG_SIZE, result);
result = -EINVAL;
goto err;
}
length = max((int) le16_to_cpu(desc->wTotalLength),
USB_DT_CONFIG_SIZE);
/* Now that we know the length, get the whole thing */
bigbuffer = kmalloc(length, GFP_KERNEL);
if (!bigbuffer) {
result = -ENOMEM;
goto err;
}
if (dev->quirks & USB_QUIRK_DELAY_INIT)
msleep(200);
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
bigbuffer, length);
if (result < 0) {
dev_err(ddev, "unable to read config index %d "
"descriptor/%s\n", cfgno, "all");
kfree(bigbuffer);
goto err;
}
if (result < length) {
dev_warn(ddev, "config index %d descriptor too short "
"(expected %i, got %i)\n", cfgno, length, result);
length = result;
}
dev->rawdescriptors[cfgno] = bigbuffer;
result = usb_parse_configuration(dev, cfgno,
&dev->config[cfgno], bigbuffer, length);
if (result < 0) {
++cfgno;
goto err;
}
}
result = 0;
err:
kfree(desc);
dev->descriptor.bNumConfigurations = cfgno;
err2:
if (result == -ENOMEM)
dev_err(ddev, "out of memory\n");
return result;
}
void usb_release_bos_descriptor(struct usb_device *dev)
{
if (dev->bos) {
kfree(dev->bos->desc);
kfree(dev->bos);
dev->bos = NULL;
}
}
/* Get BOS descriptor set */
int usb_get_bos_descriptor(struct usb_device *dev)
{
struct device *ddev = &dev->dev;
struct usb_bos_descriptor *bos;
struct usb_dev_cap_header *cap;
unsigned char *buffer;
int length, total_len, num, i;
int ret;
bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);
if (!bos)
return -ENOMEM;
/* Get BOS descriptor */
ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);
if (ret < USB_DT_BOS_SIZE) {
dev_err(ddev, "unable to get BOS descriptor\n");
if (ret >= 0)
ret = -ENOMSG;
kfree(bos);
return ret;
}
length = bos->bLength;
total_len = le16_to_cpu(bos->wTotalLength);
num = bos->bNumDeviceCaps;
kfree(bos);
if (total_len < length)
return -EINVAL;
dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);
if (!dev->bos)
return -ENOMEM;
/* Now let's get the whole BOS descriptor set */
buffer = kzalloc(total_len, GFP_KERNEL);
if (!buffer) {
ret = -ENOMEM;
goto err;
}
dev->bos->desc = (struct usb_bos_descriptor *)buffer;
ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);
if (ret < total_len) {
dev_err(ddev, "unable to get BOS descriptor set\n");
if (ret >= 0)
ret = -ENOMSG;
goto err;
}
total_len -= length;
for (i = 0; i < num; i++) {
buffer += length;
cap = (struct usb_dev_cap_header *)buffer;
length = cap->bLength;
if (total_len < length)
break;
total_len -= length;
if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {
dev_warn(ddev, "descriptor type invalid, skip\n");
continue;
}
switch (cap->bDevCapabilityType) {
case USB_CAP_TYPE_WIRELESS_USB:
/* Wireless USB cap descriptor is handled by wusb */
break;
case USB_CAP_TYPE_EXT:
dev->bos->ext_cap =
(struct usb_ext_cap_descriptor *)buffer;
break;
case USB_SS_CAP_TYPE:
dev->bos->ss_cap =
(struct usb_ss_cap_descriptor *)buffer;
break;
case USB_SSP_CAP_TYPE:
dev->bos->ssp_cap =
(struct usb_ssp_cap_descriptor *)buffer;
break;
case CONTAINER_ID_TYPE:
dev->bos->ss_id =
(struct usb_ss_container_id_descriptor *)buffer;
break;
case USB_PTM_CAP_TYPE:
dev->bos->ptm_cap =
(struct usb_ptm_cap_descriptor *)buffer;
default:
break;
}
}
return 0;
err:
usb_release_bos_descriptor(dev);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2916_0 |
crossvul-cpp_data_bad_926_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD %
% T H H R R E SS H H O O L D D %
% T HHHHH RRRR EEE SSS HHHHH O O L D D %
% T H H R R E SS H H O O L D D %
% T H H R R EEEEE SSSSS H H OOO LLLLL DDDD %
% %
% %
% MagickCore Image Threshold Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/property.h"
#include "magick/blob.h"
#include "magick/cache-view.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/configure.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/effect.h"
#include "magick/fx.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/montage.h"
#include "magick/option.h"
#include "magick/pixel-private.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/shear.h"
#include "magick/signature-private.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/transform.h"
#include "magick/xml-tree.h"
/*
Define declarations.
*/
#define ThresholdsFilename "thresholds.xml"
/*
Typedef declarations.
*/
struct _ThresholdMap
{
char
*map_id,
*description;
size_t
width,
height;
ssize_t
divisor,
*levels;
};
/*
Static declarations.
*/
static const char
*MinimalThresholdMap =
"<?xml version=\"1.0\"?>"
"<thresholds>"
" <threshold map=\"threshold\" alias=\"1x1\">"
" <description>Threshold 1x1 (non-dither)</description>"
" <levels width=\"1\" height=\"1\" divisor=\"2\">"
" 1"
" </levels>"
" </threshold>"
" <threshold map=\"checks\" alias=\"2x1\">"
" <description>Checkerboard 2x1 (dither)</description>"
" <levels width=\"2\" height=\"2\" divisor=\"3\">"
" 1 2"
" 2 1"
" </levels>"
" </threshold>"
"</thresholds>";
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveThresholdImage() selects an individual threshold for each pixel
% based on the range of intensity values in its local neighborhood. This
% allows for thresholding of an image whose global intensity histogram
% doesn't contain distinctive peaks.
%
% The format of the AdaptiveThresholdImage method is:
%
% Image *AdaptiveThresholdImage(const Image *image,
% const size_t width,const size_t height,
% const ssize_t offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the local neighborhood.
%
% o height: the height of the local neighborhood.
%
% o offset: the mean offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoThresholdImage() automatically performs image thresholding
% dependent on which method you specify.
%
% The format of the AutoThresholdImage method is:
%
% MagickBooleanType AutoThresholdImage(Image *image,
% const AutoThresholdMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-threshold.
%
% o method: choose from Kapur, OTSU, or Triangle.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double KapurThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
#define MaxIntensity 255
double
*black_entropy,
*cumulative_histogram,
entropy,
epsilon,
maximum_entropy,
*white_entropy;
register ssize_t
i,
j;
size_t
threshold;
/*
Compute optimal threshold from the entopy of the histogram.
*/
cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*cumulative_histogram));
black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*black_entropy));
white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*white_entropy));
if ((cumulative_histogram == (double *) NULL) ||
(black_entropy == (double *) NULL) || (white_entropy == (double *) NULL))
{
if (white_entropy != (double *) NULL)
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
if (black_entropy != (double *) NULL)
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
if (cumulative_histogram != (double *) NULL)
cumulative_histogram=(double *)
RelinquishMagickMemory(cumulative_histogram);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Entropy for black and white parts of the histogram.
*/
cumulative_histogram[0]=histogram[0];
for (i=1; i <= MaxIntensity; i++)
cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i];
epsilon=MagickMinimumValue;
for (j=0; j <= MaxIntensity; j++)
{
/*
Black entropy.
*/
black_entropy[j]=0.0;
if (cumulative_histogram[j] > epsilon)
{
entropy=0.0;
for (i=0; i <= j; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/cumulative_histogram[j]*
log(histogram[i]/cumulative_histogram[j]);
black_entropy[j]=entropy;
}
/*
White entropy.
*/
white_entropy[j]=0.0;
if ((1.0-cumulative_histogram[j]) > epsilon)
{
entropy=0.0;
for (i=j+1; i <= MaxIntensity; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/(1.0-cumulative_histogram[j])*
log(histogram[i]/(1.0-cumulative_histogram[j]));
white_entropy[j]=entropy;
}
}
/*
Find histogram bin with maximum entropy.
*/
maximum_entropy=black_entropy[0]+white_entropy[0];
threshold=0;
for (j=1; j <= MaxIntensity; j++)
if ((black_entropy[j]+white_entropy[j]) > maximum_entropy)
{
maximum_entropy=black_entropy[j]+white_entropy[j];
threshold=(size_t) j;
}
/*
Free resources.
*/
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram);
return(100.0*threshold/MaxIntensity);
}
static double OTSUThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
double
max_sigma,
*myu,
*omega,
*probability,
*sigma,
threshold;
register ssize_t
i;
/*
Compute optimal threshold from maximization of inter-class variance.
*/
myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu));
omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega));
probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*probability));
sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma));
if ((myu == (double *) NULL) || (omega == (double *) NULL) ||
(probability == (double *) NULL) || (sigma == (double *) NULL))
{
if (sigma != (double *) NULL)
sigma=(double *) RelinquishMagickMemory(sigma);
if (probability != (double *) NULL)
probability=(double *) RelinquishMagickMemory(probability);
if (omega != (double *) NULL)
omega=(double *) RelinquishMagickMemory(omega);
if (myu != (double *) NULL)
myu=(double *) RelinquishMagickMemory(myu);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Calculate probability density.
*/
for (i=0; i <= (ssize_t) MaxIntensity; i++)
probability[i]=histogram[i];
/*
Generate probability of graylevels and mean value for separation.
*/
omega[0]=probability[0];
myu[0]=0.0;
for (i=1; i <= (ssize_t) MaxIntensity; i++)
{
omega[i]=omega[i-1]+probability[i];
myu[i]=myu[i-1]+i*probability[i];
}
/*
Sigma maximization: inter-class variance and compute optimal threshold.
*/
threshold=0;
max_sigma=0.0;
for (i=0; i < (ssize_t) MaxIntensity; i++)
{
sigma[i]=0.0;
if ((omega[i] != 0.0) && (omega[i] != 1.0))
sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0-
omega[i]));
if (sigma[i] > max_sigma)
{
max_sigma=sigma[i];
threshold=(double) i;
}
}
/*
Free resources.
*/
myu=(double *) RelinquishMagickMemory(myu);
omega=(double *) RelinquishMagickMemory(omega);
probability=(double *) RelinquishMagickMemory(probability);
sigma=(double *) RelinquishMagickMemory(sigma);
return(100.0*threshold/MaxIntensity);
}
static double TriangleThreshold(const Image *image,const double *histogram)
{
double
a,
b,
c,
count,
distance,
inverse_ratio,
max_distance,
segment,
x1,
x2,
y1,
y2;
register ssize_t
i;
ssize_t
end,
max,
start,
threshold;
/*
Compute optimal threshold with triangle algorithm.
*/
start=0; /* find start bin, first bin not zero count */
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > 0.0)
{
start=i;
break;
}
end=0; /* find end bin, last bin not zero count */
for (i=(ssize_t) MaxIntensity; i >= 0; i--)
if (histogram[i] > 0.0)
{
end=i;
break;
}
max=0; /* find max bin, bin with largest count */
count=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > count)
{
max=i;
count=histogram[i];
}
/*
Compute threshold at split point.
*/
x1=(double) max;
y1=histogram[max];
x2=(double) end;
if ((max-start) >= (end-max))
x2=(double) start;
y2=0.0;
a=y1-y2;
b=x2-x1;
c=(-1.0)*(a*x1+b*y1);
inverse_ratio=1.0/sqrt(a*a+b*b+c*c);
threshold=0;
max_distance=0.0;
if (x2 == (double) start)
for (i=start; i < max; i++)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment > 0.0))
{
threshold=i;
max_distance=distance;
}
}
else
for (i=end; i > max; i--)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment < 0.0))
{
threshold=i;
max_distance=distance;
}
}
return(100.0*threshold/MaxIntensity);
}
MagickExport MagickBooleanType AutoThresholdImage(Image *image,
const AutoThresholdMethod method,ExceptionInfo *exception)
{
CacheView
*image_view;
char
property[MagickPathExtent];
double
gamma,
*histogram,
sum,
threshold;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
y;
/*
Form histogram.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
(void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
double intensity = GetPixelIntensity(image,p);
histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++;
p++;
}
}
image_view=DestroyCacheView(image_view);
/*
Normalize histogram.
*/
sum=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
sum+=histogram[i];
gamma=PerceptibleReciprocal(sum);
for (i=0; i <= (ssize_t) MaxIntensity; i++)
histogram[i]=gamma*histogram[i];
/*
Discover threshold from histogram.
*/
switch (method)
{
case KapurThresholdMethod:
{
threshold=KapurThreshold(image,histogram,exception);
break;
}
case OTSUThresholdMethod:
default:
{
threshold=OTSUThreshold(image,histogram,exception);
break;
}
case TriangleThresholdMethod:
{
threshold=TriangleThreshold(image,histogram);
break;
}
}
histogram=(double *) RelinquishMagickMemory(histogram);
if (threshold < 0.0)
status=MagickFalse;
if (status == MagickFalse)
return(MagickFalse);
/*
Threshold image.
*/
(void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold);
(void) SetImageProperty(image,"auto-threshold:threshold",property);
return(BilevelImage(image,QuantumRange*threshold/100.0));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B i l e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BilevelImage() changes the value of individual pixels based on the
% intensity of each pixel channel. The result is a high-contrast image.
%
% More precisely each channel value of the image is 'thresholded' so that if
% it is equal to or less than the given value it is set to zero, while any
% value greater than that give is set to it maximum or QuantumRange.
%
% This function is what is used to implement the "-threshold" operator for
% the command line API.
%
% If the default channel setting is given the image is thresholded using just
% the gray 'intensity' of the image, rather than the individual channels.
%
% The format of the BilevelImageChannel method is:
%
% MagickBooleanType BilevelImage(Image *image,const double threshold)
% MagickBooleanType BilevelImageChannel(Image *image,
% const ChannelType channel,const double threshold)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o threshold: define the threshold values.
%
% Aside: You can get the same results as operator using LevelImageChannels()
% with the 'threshold' value for both the black_point and the white_point.
%
*/
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold)
{
MagickBooleanType
status;
status=BilevelImageChannel(image,DefaultChannels,threshold);
return(status);
}
MagickExport MagickBooleanType BilevelImageChannel(Image *image,
const ChannelType channel,const double threshold)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
/*
Bilevel threshold image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if ((channel & SyncChannels) != 0)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 :
QuantumRange);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 :
QuantumRange);
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 :
QuantumRange);
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 :
QuantumRange);
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold ? 0 : QuantumRange);
else
SetPixelAlpha(q,(MagickRealType) GetPixelAlpha(q) <= threshold ?
OpaqueOpacity : TransparentOpacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <=
threshold ? 0 : QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l a c k T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlackThresholdImage() is like ThresholdImage() but forces all pixels below
% the threshold into black while leaving all pixels at or above the threshold
% unchanged.
%
% The format of the BlackThresholdImage method is:
%
% MagickBooleanType BlackThresholdImage(Image *image,const char *threshold)
% MagickBooleanType BlackThresholdImageChannel(Image *image,
% const ChannelType channel,const char *threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
const char *threshold)
{
MagickBooleanType
status;
status=BlackThresholdImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
GetMagickPixelPacket(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold.green=threshold.red;
threshold.blue=geometry_info.xi;
if ((flags & XiValue) == 0)
threshold.blue=threshold.red;
threshold.opacity=geometry_info.psi;
if ((flags & PsiValue) == 0)
threshold.opacity=threshold.red;
threshold.index=geometry_info.chi;
if ((flags & ChiValue) == 0)
threshold.index=threshold.red;
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.opacity*=(MagickRealType) (QuantumRange/100.0);
threshold.index*=(MagickRealType) (QuantumRange/100.0);
}
if ((IsMagickGray(&threshold) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace);
/*
Black threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetPixelRed(q) < threshold.red))
SetPixelRed(q,0);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetPixelGreen(q) < threshold.green))
SetPixelGreen(q,0);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetPixelBlue(q) < threshold.blue))
SetPixelBlue(q,0);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetPixelOpacity(q) < threshold.opacity))
SetPixelOpacity(q,0);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetPixelIndex(indexes+x) < threshold.index))
SetPixelIndex(indexes+x,0);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l a m p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampImage() set each pixel whose value is below zero to zero and any the
% pixel whose value is above the quantum range to the quantum range (e.g.
% 65535) otherwise the pixel value remains unchanged.
%
% The format of the ClampImageChannel method is:
%
% MagickBooleanType ClampImage(Image *image)
% MagickBooleanType ClampImageChannel(Image *image,
% const ChannelType channel)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
*/
MagickExport MagickBooleanType ClampImage(Image *image)
{
MagickBooleanType
status;
status=ClampImageChannel(image,DefaultChannels);
return(status);
}
MagickExport MagickBooleanType ClampImageChannel(Image *image,
const ChannelType channel)
{
#define ClampImageTag "Clamp/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelPacket
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q)));
SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q)));
SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q)));
SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q)));
q++;
}
return(SyncImage(image));
}
/*
Clamp image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q)));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q)));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q)));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q)));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,ClampPixel((MagickRealType) GetPixelIndex(
indexes+x)));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ClampImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyThresholdMap() de-allocate the given ThresholdMap
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *DestroyThresholdMap(Threshold *map)
%
% A description of each parameter follows.
%
% o map: Pointer to the Threshold map to destroy
%
*/
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
{
assert(map != (ThresholdMap *) NULL);
if (map->map_id != (char *) NULL)
map->map_id=DestroyString(map->map_id);
if (map->description != (char *) NULL)
map->description=DestroyString(map->description);
if (map->levels != (ssize_t *) NULL)
map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
map=(ThresholdMap *) RelinquishMagickMemory(map);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMapFile() look for a given threshold map name or alias in the
% given XML file data, and return the allocated the map when found.
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
% const char *map_id,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o map_id: ID of the map to look for in XML list.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMapFile(const char *xml,
const char *filename,const char *map_id,ExceptionInfo *exception)
{
const char
*attribute,
*content;
double
value;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
map = (ThresholdMap *) NULL;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(map);
for (threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold = GetNextXMLTreeTag(threshold) )
{
attribute=GetXMLTreeAttribute(threshold, "map");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(threshold, "alias");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
}
if (threshold == (XMLTreeInfo *) NULL)
{
thresholds=DestroyXMLTree(thresholds);
return(map);
}
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
levels=GetXMLTreeChild(threshold,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
The map has been found -- allocate a Threshold Map to return
*/
map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap));
if (map == (ThresholdMap *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
map->map_id=(char *) NULL;
map->description=(char *) NULL;
map->levels=(ssize_t *) NULL;
/*
Assign basic attributeibutes.
*/
attribute=GetXMLTreeAttribute(threshold,"map");
if (attribute != (char *) NULL)
map->map_id=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
map->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->width=StringToUnsignedLong(attribute);
if (map->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->height=StringToUnsignedLong(attribute);
if (map->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels, "divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->divisor=(ssize_t) StringToLong(attribute);
if (map->divisor < 2)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
/*
Allocate theshold levels array.
*/
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if (map->levels == (ssize_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
{
char
*p;
register ssize_t
i;
/*
Parse levels into integer array.
*/
for (i=0; i< (ssize_t) (map->width*map->height); i++)
{
map->levels[i]=(ssize_t) strtol(content,&p,10);
if (p == content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
}
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMap() load and search one or more threshold map files for the
% a map matching the given name or aliase.
%
% The format of the GetThresholdMap method is:
%
% ThresholdMap *GetThresholdMap(const char *map_id,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o map_id: ID of the map to look for.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
ThresholdMap
*map;
map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
options=GetConfigureOptions(ThresholdsFilename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),map_id,exception);
if (map != (ThresholdMap *) NULL)
break;
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L i s t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMapFile() lists the threshold maps and their descriptions
% in the given XML file data.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
% const char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
const char *filename,ExceptionInfo *exception)
{
XMLTreeInfo *thresholds,*threshold,*description;
const char *map,*alias,*content;
assert( xml != (char *) NULL );
assert( file != (FILE *) NULL );
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(MagickFalse);
(void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
(void) FormatLocaleFile(file,
"----------------------------------------------------\n");
for( threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold = GetNextXMLTreeTag(threshold) )
{
map = GetXMLTreeAttribute(threshold, "map");
if (map == (char *) NULL) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<map>");
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
alias = GetXMLTreeAttribute(threshold, "alias");
/* alias is optional, no if test needed */
description=GetXMLTreeChild(threshold,"description");
if ( description == (XMLTreeInfo *) NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
content=GetXMLTreeContent(description);
if ( content == (char *) NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
content);
}
thresholds=DestroyXMLTree(thresholds);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t T h r e s h o l d M a p s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMaps() lists the threshold maps and their descriptions
% as defined by "threshold.xml" to a file.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
MagickStatusType
status;
status=MagickTrue;
if (file == (FILE *) NULL)
file=stdout;
options=GetConfigureOptions(ThresholdsFilename,exception);
(void) FormatLocaleFile(file,
"\n Threshold Maps for Ordered Dither Operations\n");
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
(void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedDitherImage() uses the ordered dithering technique of reducing color
% images to monochrome using positional information to retain as much
% information as possible.
%
% WARNING: This function is deprecated, and is now just a call to
% the more more powerful OrderedPosterizeImage(); function.
%
% The format of the OrderedDitherImage method is:
%
% MagickBooleanType OrderedDitherImage(Image *image)
% MagickBooleanType OrderedDitherImageChannel(Image *image,
% const ChannelType channel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedDitherImage(Image *image)
{
MagickBooleanType
status;
status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception);
return(status);
}
MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image,
const ChannelType channel,ExceptionInfo *exception)
{
MagickBooleanType
status;
/*
Call the augumented function OrderedPosterizeImage()
*/
status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d P o s t e r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedPosterizeImage() will perform a ordered dither based on a number
% of pre-defined dithering threshold maps, but over multiple intensity
% levels, which can be different for different channels, according to the
% input argument.
%
% The format of the OrderedPosterizeImage method is:
%
% MagickBooleanType OrderedPosterizeImage(Image *image,
% const char *threshold_map,ExceptionInfo *exception)
% MagickBooleanType OrderedPosterizeImageChannel(Image *image,
% const ChannelType channel,const char *threshold_map,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold_map: A string containing the name of the threshold dither
% map to use, followed by zero or more numbers representing the number
% of color levels tho dither between.
%
% Any level number less than 2 will be equivalent to 2, and means only
% binary dithering will be applied to each color channel.
%
% No numbers also means a 2 level (bitmap) dither will be applied to all
% channels, while a single number is the number of levels applied to each
% channel in sequence. More numbers will be applied in turn to each of
% the color channels.
%
% For example: "o3x3,6" will generate a 6 level posterization of the
% image with a ordered 3x3 diffused pixel dither being applied between
% each level. While checker,8,8,4 will produce a 332 colormaped image
% with only a single checkerboard hash pattern (50% grey) between each
% color level, to basically double the number of color levels with
% a bare minimim of dithering.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
const char *threshold_map,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map,
exception);
return(status);
}
MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image,
const ChannelType channel,const char *threshold_map,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
LongPixelPacket
levels;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
ThresholdMap
*map;
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);
if (threshold_map == (const char *) NULL)
return(MagickTrue);
{
char
token[MaxTextExtent];
register const char
*p;
p=(char *)threshold_map;
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
threshold_map=p;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0')) {
if ((p-threshold_map) >= (MaxTextExtent-1))
break;
token[p-threshold_map] = *p;
p++;
}
token[p-threshold_map] = '\0';
map = GetThresholdMap(token, exception);
if ( map == (ThresholdMap *) NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
return(MagickFalse);
}
}
/* Set channel levels from extra comma separated arguments
Default to 2, the single value given, or individual channel values
*/
#if 1
{ /* parse directly as a comma separated list of integers */
char *p;
p = strchr((char *) threshold_map,',');
if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) )
levels.index = (unsigned int) strtoul(p, &p, 10);
else
levels.index = 2;
levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0;
levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0;
levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0;
levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0;
levels.index = ((channel & IndexChannel) != 0
&& (image->colorspace == CMYKColorspace)) ? levels.index : 0;
/* if more than a single number, each channel has a separate value */
if ( p != (char *) NULL && *p == ',' ) {
p=strchr((char *) threshold_map,',');
p++;
if ((channel & RedChannel) != 0)
levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & GreenChannel) != 0)
levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & BlueChannel) != 0)
levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace)
levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & OpacityChannel) != 0)
levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
}
}
#else
/* Parse level values as a geometry */
/* This difficult!
* How to map GeometryInfo structure elements into
* LongPixelPacket structure elements, but according to channel?
* Note the channels list may skip elements!!!!
* EG -channel BA -ordered-dither map,2,3
* will need to map g.rho -> l.blue, and g.sigma -> l.opacity
* A simpler way is needed, probably converting geometry to a temporary
* array, then using channel to advance the index into ssize_t pixel packet.
*/
#endif
#if 0
printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n",
levels.red, levels.green, levels.blue, levels.opacity, levels.index);
#endif
{ /* Do the posterized ordered dithering of the image */
ssize_t
d;
/* d = number of psuedo-level divisions added between color levels */
d = map->divisor-1;
/* reduce levels to levels - 1 */
levels.red = levels.red ? levels.red-1 : 0;
levels.green = levels.green ? levels.green-1 : 0;
levels.blue = levels.blue ? levels.blue-1 : 0;
levels.opacity = levels.opacity ? levels.opacity-1 : 0;
levels.index = levels.index ? levels.index-1 : 0;
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
threshold,
t,
l;
/*
Figure out the dither threshold for this pixel
This must be a integer from 1 to map->divisor-1
*/
threshold = map->levels[(x%map->width) +map->width*(y%map->height)];
/* Dither each channel in the image as appropriate
Notes on the integer Math...
total number of divisions = (levels-1)*(divisor-1)+1)
t1 = this colors psuedo_level =
q->red * total_divisions / (QuantumRange+1)
l = posterization level 0..levels
t = dither threshold level 0..divisor-1 NB: 0 only on last
Each color_level is of size QuantumRange / (levels-1)
NB: All input levels and divisor are already had 1 subtracted
Opacity is inverted so 'off' represents transparent.
*/
if (levels.red) {
t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1));
l = t/d; t = t-l*d;
SetPixelRed(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red)));
}
if (levels.green) {
t = (ssize_t) (QuantumScale*GetPixelGreen(q)*
(levels.green*d+1));
l = t/d; t = t-l*d;
SetPixelGreen(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green)));
}
if (levels.blue) {
t = (ssize_t) (QuantumScale*GetPixelBlue(q)*
(levels.blue*d+1));
l = t/d; t = t-l*d;
SetPixelBlue(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue)));
}
if (levels.opacity) {
t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))*
(levels.opacity*d+1));
l = t/d; t = t-l*d;
SetPixelOpacity(q,ClampToQuantum((MagickRealType)
((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/
levels.opacity)));
}
if (levels.index) {
t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)*
(levels.index*d+1));
l = t/d; t = t-l*d;
SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+
(t>=threshold))*(MagickRealType) QuantumRange/levels.index)));
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,DitherImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
}
map=DestroyThresholdMap(map);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P e r c e p t i b l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PerceptibleImage() set each pixel whose value is less than |epsilon| to
% epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
% unchanged.
%
% The format of the PerceptibleImageChannel method is:
%
% MagickBooleanType PerceptibleImage(Image *image,const double epsilon)
% MagickBooleanType PerceptibleImageChannel(Image *image,
% const ChannelType channel,const double epsilon)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o epsilon: the epsilon threshold (e.g. 1.0e-9).
%
*/
static inline Quantum PerceptibleThreshold(const Quantum quantum,
const double epsilon)
{
double
sign;
sign=(double) quantum < 0.0 ? -1.0 : 1.0;
if ((sign*quantum) >= epsilon)
return(quantum);
return((Quantum) (sign*epsilon));
}
MagickExport MagickBooleanType PerceptibleImage(Image *image,
const double epsilon)
{
MagickBooleanType
status;
status=PerceptibleImageChannel(image,DefaultChannels,epsilon);
return(status);
}
MagickExport MagickBooleanType PerceptibleImageChannel(Image *image,
const ChannelType channel,const double epsilon)
{
#define PerceptibleImageTag "Perceptible/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelPacket
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon));
SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon));
SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon));
SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon));
q++;
}
return(SyncImage(image));
}
/*
Perceptible image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x),
epsilon));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,PerceptibleImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n d o m T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RandomThresholdImage() changes the value of individual pixels based on the
% intensity of each pixel compared to a random threshold. The result is a
% low-contrast, two color image.
%
% The format of the RandomThresholdImage method is:
%
% MagickBooleanType RandomThresholdImageChannel(Image *image,
% const char *thresholds,ExceptionInfo *exception)
% MagickBooleanType RandomThresholdImageChannel(Image *image,
% const ChannelType channel,const char *thresholds,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o thresholds: a geometry string containing low,high thresholds. If the
% string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4
% is performed instead.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=RandomThresholdImageChannel(image,DefaultChannels,thresholds,
exception);
return(status);
}
MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickStatusType
flags;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickRealType
min_threshold,
max_threshold;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
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);
if (thresholds == (const char *) NULL)
return(MagickTrue);
GetMagickPixelPacket(image,&threshold);
min_threshold=0.0;
max_threshold=(MagickRealType) QuantumRange;
flags=ParseGeometry(thresholds,&geometry_info);
min_threshold=geometry_info.rho;
max_threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
max_threshold=min_threshold;
if (strchr(thresholds,'%') != (char *) NULL)
{
max_threshold*=(MagickRealType) (0.01*QuantumRange);
min_threshold*=(MagickRealType) (0.01*QuantumRange);
}
else
if (((max_threshold == min_threshold) || (max_threshold == 1)) &&
(min_threshold <= 8))
{
/*
Backward Compatibility -- ordered-dither -- IM v 6.2.9-6.
*/
status=OrderedPosterizeImageChannel(image,channel,thresholds,exception);
return(status);
}
/*
Random threshold image.
*/
status=MagickTrue;
progress=0;
if (channel == CompositeChannels)
{
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
IndexPacket
index;
MagickRealType
intensity;
intensity=GetPixelIntensity(image,q);
if (intensity < min_threshold)
threshold.index=min_threshold;
else if (intensity > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType)(QuantumRange*
GetPseudoRandomValue(random_info[id]));
index=(IndexPacket) (intensity <= threshold.index ? 0 : 1);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
if ((MagickRealType) GetPixelRed(q) < min_threshold)
threshold.red=min_threshold;
else
if ((MagickRealType) GetPixelRed(q) > max_threshold)
threshold.red=max_threshold;
else
threshold.red=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & GreenChannel) != 0)
{
if ((MagickRealType) GetPixelGreen(q) < min_threshold)
threshold.green=min_threshold;
else
if ((MagickRealType) GetPixelGreen(q) > max_threshold)
threshold.green=max_threshold;
else
threshold.green=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & BlueChannel) != 0)
{
if ((MagickRealType) GetPixelBlue(q) < min_threshold)
threshold.blue=min_threshold;
else
if ((MagickRealType) GetPixelBlue(q) > max_threshold)
threshold.blue=max_threshold;
else
threshold.blue=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & OpacityChannel) != 0)
{
if ((MagickRealType) GetPixelOpacity(q) < min_threshold)
threshold.opacity=min_threshold;
else
if ((MagickRealType) GetPixelOpacity(q) > max_threshold)
threshold.opacity=max_threshold;
else
threshold.opacity=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold)
threshold.index=min_threshold;
else
if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ?
0 : QuantumRange);
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ?
0 : QuantumRange);
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ?
0 : QuantumRange);
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold.opacity ? 0 : QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <=
threshold.index ? 0 : QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W h i t e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
% the threshold into white while leaving all pixels at or below the threshold
% unchanged.
%
% The format of the WhiteThresholdImage method is:
%
% MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold)
% MagickBooleanType WhiteThresholdImageChannel(Image *image,
% const ChannelType channel,const char *threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
const char *threshold)
{
MagickBooleanType
status;
status=WhiteThresholdImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
flags=ParseGeometry(thresholds,&geometry_info);
GetMagickPixelPacket(image,&threshold);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold.green=threshold.red;
threshold.blue=geometry_info.xi;
if ((flags & XiValue) == 0)
threshold.blue=threshold.red;
threshold.opacity=geometry_info.psi;
if ((flags & PsiValue) == 0)
threshold.opacity=threshold.red;
threshold.index=geometry_info.chi;
if ((flags & ChiValue) == 0)
threshold.index=threshold.red;
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.opacity*=(MagickRealType) (QuantumRange/100.0);
threshold.index*=(MagickRealType) (QuantumRange/100.0);
}
if ((IsMagickGray(&threshold) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace);
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetPixelRed(q) > threshold.red))
SetPixelRed(q,QuantumRange);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetPixelGreen(q) > threshold.green))
SetPixelGreen(q,QuantumRange);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetPixelBlue(q) > threshold.blue))
SetPixelBlue(q,QuantumRange);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetPixelOpacity(q) > threshold.opacity))
SetPixelOpacity(q,QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index)
SetPixelIndex(indexes+x,QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_926_0 |
crossvul-cpp_data_bad_5491_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) {
xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (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) % (1 << rpx)))
|| !(pi->x % (1 << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy)))
|| !(pi->y % (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) {
xstep = picomp->hsamp * (1 <<
(pirlvl->prcwidthexpn + picomp->numrlvls -
rlvlno - 1));
ystep = picomp->vsamp * (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) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (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;
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) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (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/bad_5491_1 |
crossvul-cpp_data_good_2692_0 | /*
* Copyright (C) 1998 and 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.
*/
/* \summary: IPv6 DHCP printer */
/*
* RFC3315: DHCPv6
* supported DHCPv6 options:
* RFC3319: Session Initiation Protocol (SIP) Servers options,
* RFC3633: IPv6 Prefix options,
* RFC3646: DNS Configuration options,
* RFC3898: Network Information Service (NIS) Configuration options,
* RFC4075: Simple Network Time Protocol (SNTP) Configuration option,
* RFC4242: Information Refresh Time option,
* RFC4280: Broadcast and Multicast Control Servers options,
* RFC5908: Network Time Protocol (NTP) Server Option for DHCPv6
* RFC6334: Dual-Stack Lite option,
*/
#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"
/* lease duration */
#define DHCP6_DURATION_INFINITE 0xffffffff
/* Error Values */
#define DH6ERR_FAILURE 16
#define DH6ERR_AUTHFAIL 17
#define DH6ERR_POORLYFORMED 18
#define DH6ERR_UNAVAIL 19
#define DH6ERR_OPTUNAVAIL 20
/* Message type */
#define DH6_SOLICIT 1
#define DH6_ADVERTISE 2
#define DH6_REQUEST 3
#define DH6_CONFIRM 4
#define DH6_RENEW 5
#define DH6_REBIND 6
#define DH6_REPLY 7
#define DH6_RELEASE 8
#define DH6_DECLINE 9
#define DH6_RECONFIGURE 10
#define DH6_INFORM_REQ 11
#define DH6_RELAY_FORW 12
#define DH6_RELAY_REPLY 13
#define DH6_LEASEQUERY 14
#define DH6_LQ_REPLY 15
static const struct tok dh6_msgtype_str[] = {
{ DH6_SOLICIT, "solicit" },
{ DH6_ADVERTISE, "advertise" },
{ DH6_REQUEST, "request" },
{ DH6_CONFIRM, "confirm" },
{ DH6_RENEW, "renew" },
{ DH6_REBIND, "rebind" },
{ DH6_REPLY, "reply" },
{ DH6_RELEASE, "release" },
{ DH6_DECLINE, "decline" },
{ DH6_RECONFIGURE, "reconfigure" },
{ DH6_INFORM_REQ, "inf-req" },
{ DH6_RELAY_FORW, "relay-fwd" },
{ DH6_RELAY_REPLY, "relay-reply" },
{ DH6_LEASEQUERY, "leasequery" },
{ DH6_LQ_REPLY, "leasequery-reply" },
{ 0, NULL }
};
/* DHCP6 base packet format */
struct dhcp6 {
union {
nd_uint8_t m;
nd_uint32_t x;
} dh6_msgtypexid;
/* options follow */
};
#define dh6_msgtype dh6_msgtypexid.m
#define dh6_xid dh6_msgtypexid.x
#define DH6_XIDMASK 0x00ffffff
/* DHCPv6 relay messages */
struct dhcp6_relay {
nd_uint8_t dh6relay_msgtype;
nd_uint8_t dh6relay_hcnt;
nd_uint8_t dh6relay_linkaddr[16]; /* XXX: badly aligned */
nd_uint8_t dh6relay_peeraddr[16];
/* options follow */
};
/* options */
#define DH6OPT_CLIENTID 1
#define DH6OPT_SERVERID 2
#define DH6OPT_IA_NA 3
#define DH6OPT_IA_TA 4
#define DH6OPT_IA_ADDR 5
#define DH6OPT_ORO 6
#define DH6OPT_PREFERENCE 7
# define DH6OPT_PREF_MAX 255
#define DH6OPT_ELAPSED_TIME 8
#define DH6OPT_RELAY_MSG 9
/*#define DH6OPT_SERVER_MSG 10 deprecated */
#define DH6OPT_AUTH 11
# define DH6OPT_AUTHPROTO_DELAYED 2
# define DH6OPT_AUTHPROTO_RECONFIG 3
# define DH6OPT_AUTHALG_HMACMD5 1
# define DH6OPT_AUTHRDM_MONOCOUNTER 0
# define DH6OPT_AUTHRECONFIG_KEY 1
# define DH6OPT_AUTHRECONFIG_HMACMD5 2
#define DH6OPT_UNICAST 12
#define DH6OPT_STATUS_CODE 13
# define DH6OPT_STCODE_SUCCESS 0
# define DH6OPT_STCODE_UNSPECFAIL 1
# define DH6OPT_STCODE_NOADDRAVAIL 2
# define DH6OPT_STCODE_NOBINDING 3
# define DH6OPT_STCODE_NOTONLINK 4
# define DH6OPT_STCODE_USEMULTICAST 5
# define DH6OPT_STCODE_NOPREFIXAVAIL 6
# define DH6OPT_STCODE_UNKNOWNQUERYTYPE 7
# define DH6OPT_STCODE_MALFORMEDQUERY 8
# define DH6OPT_STCODE_NOTCONFIGURED 9
# define DH6OPT_STCODE_NOTALLOWED 10
#define DH6OPT_RAPID_COMMIT 14
#define DH6OPT_USER_CLASS 15
#define DH6OPT_VENDOR_CLASS 16
#define DH6OPT_VENDOR_OPTS 17
#define DH6OPT_INTERFACE_ID 18
#define DH6OPT_RECONF_MSG 19
#define DH6OPT_RECONF_ACCEPT 20
#define DH6OPT_SIP_SERVER_D 21
#define DH6OPT_SIP_SERVER_A 22
#define DH6OPT_DNS_SERVERS 23
#define DH6OPT_DOMAIN_LIST 24
#define DH6OPT_IA_PD 25
#define DH6OPT_IA_PD_PREFIX 26
#define DH6OPT_NIS_SERVERS 27
#define DH6OPT_NISP_SERVERS 28
#define DH6OPT_NIS_NAME 29
#define DH6OPT_NISP_NAME 30
#define DH6OPT_SNTP_SERVERS 31
#define DH6OPT_LIFETIME 32
#define DH6OPT_BCMCS_SERVER_D 33
#define DH6OPT_BCMCS_SERVER_A 34
#define DH6OPT_GEOCONF_CIVIC 36
#define DH6OPT_REMOTE_ID 37
#define DH6OPT_SUBSCRIBER_ID 38
#define DH6OPT_CLIENT_FQDN 39
#define DH6OPT_PANA_AGENT 40
#define DH6OPT_NEW_POSIX_TIMEZONE 41
#define DH6OPT_NEW_TZDB_TIMEZONE 42
#define DH6OPT_ERO 43
#define DH6OPT_LQ_QUERY 44
#define DH6OPT_CLIENT_DATA 45
#define DH6OPT_CLT_TIME 46
#define DH6OPT_LQ_RELAY_DATA 47
#define DH6OPT_LQ_CLIENT_LINK 48
#define DH6OPT_NTP_SERVER 56
# define DH6OPT_NTP_SUBOPTION_SRV_ADDR 1
# define DH6OPT_NTP_SUBOPTION_MC_ADDR 2
# define DH6OPT_NTP_SUBOPTION_SRV_FQDN 3
#define DH6OPT_AFTR_NAME 64
#define DH6OPT_MUDURL 112
static const struct tok dh6opt_str[] = {
{ DH6OPT_CLIENTID, "client-ID" },
{ DH6OPT_SERVERID, "server-ID" },
{ DH6OPT_IA_NA, "IA_NA" },
{ DH6OPT_IA_TA, "IA_TA" },
{ DH6OPT_IA_ADDR, "IA_ADDR" },
{ DH6OPT_ORO, "option-request" },
{ DH6OPT_PREFERENCE, "preference" },
{ DH6OPT_ELAPSED_TIME, "elapsed-time" },
{ DH6OPT_RELAY_MSG, "relay-message" },
{ DH6OPT_AUTH, "authentication" },
{ DH6OPT_UNICAST, "server-unicast" },
{ DH6OPT_STATUS_CODE, "status-code" },
{ DH6OPT_RAPID_COMMIT, "rapid-commit" },
{ DH6OPT_USER_CLASS, "user-class" },
{ DH6OPT_VENDOR_CLASS, "vendor-class" },
{ DH6OPT_VENDOR_OPTS, "vendor-specific-info" },
{ DH6OPT_INTERFACE_ID, "interface-ID" },
{ DH6OPT_RECONF_MSG, "reconfigure-message" },
{ DH6OPT_RECONF_ACCEPT, "reconfigure-accept" },
{ DH6OPT_SIP_SERVER_D, "SIP-servers-domain" },
{ DH6OPT_SIP_SERVER_A, "SIP-servers-address" },
{ DH6OPT_DNS_SERVERS, "DNS-server" },
{ DH6OPT_DOMAIN_LIST, "DNS-search-list" },
{ DH6OPT_IA_PD, "IA_PD" },
{ DH6OPT_IA_PD_PREFIX, "IA_PD-prefix" },
{ DH6OPT_SNTP_SERVERS, "SNTP-servers" },
{ DH6OPT_LIFETIME, "lifetime" },
{ DH6OPT_NIS_SERVERS, "NIS-server" },
{ DH6OPT_NISP_SERVERS, "NIS+-server" },
{ DH6OPT_NIS_NAME, "NIS-domain-name" },
{ DH6OPT_NISP_NAME, "NIS+-domain-name" },
{ DH6OPT_BCMCS_SERVER_D, "BCMCS-domain-name" },
{ DH6OPT_BCMCS_SERVER_A, "BCMCS-server" },
{ DH6OPT_GEOCONF_CIVIC, "Geoconf-Civic" },
{ DH6OPT_REMOTE_ID, "Remote-ID" },
{ DH6OPT_SUBSCRIBER_ID, "Subscriber-ID" },
{ DH6OPT_CLIENT_FQDN, "Client-FQDN" },
{ DH6OPT_PANA_AGENT, "PANA-agent" },
{ DH6OPT_NEW_POSIX_TIMEZONE, "POSIX-timezone" },
{ DH6OPT_NEW_TZDB_TIMEZONE, "POSIX-tz-database" },
{ DH6OPT_ERO, "Echo-request-option" },
{ DH6OPT_LQ_QUERY, "Lease-query" },
{ DH6OPT_CLIENT_DATA, "LQ-client-data" },
{ DH6OPT_CLT_TIME, "Clt-time" },
{ DH6OPT_LQ_RELAY_DATA, "LQ-relay-data" },
{ DH6OPT_LQ_CLIENT_LINK, "LQ-client-link" },
{ DH6OPT_NTP_SERVER, "NTP-server" },
{ DH6OPT_AFTR_NAME, "AFTR-Name" },
{ DH6OPT_MUDURL, "MUD-URL" },
{ 0, NULL }
};
static const struct tok dh6opt_stcode_str[] = {
{ DH6OPT_STCODE_SUCCESS, "Success" }, /* RFC3315 */
{ DH6OPT_STCODE_UNSPECFAIL, "UnspecFail" }, /* RFC3315 */
{ DH6OPT_STCODE_NOADDRAVAIL, "NoAddrsAvail" }, /* RFC3315 */
{ DH6OPT_STCODE_NOBINDING, "NoBinding" }, /* RFC3315 */
{ DH6OPT_STCODE_NOTONLINK, "NotOnLink" }, /* RFC3315 */
{ DH6OPT_STCODE_USEMULTICAST, "UseMulticast" }, /* RFC3315 */
{ DH6OPT_STCODE_NOPREFIXAVAIL, "NoPrefixAvail" }, /* RFC3633 */
{ DH6OPT_STCODE_UNKNOWNQUERYTYPE, "UnknownQueryType" }, /* RFC5007 */
{ DH6OPT_STCODE_MALFORMEDQUERY, "MalformedQuery" }, /* RFC5007 */
{ DH6OPT_STCODE_NOTCONFIGURED, "NotConfigured" }, /* RFC5007 */
{ DH6OPT_STCODE_NOTALLOWED, "NotAllowed" }, /* RFC5007 */
{ 0, NULL }
};
struct dhcp6opt {
nd_uint16_t dh6opt_type;
nd_uint16_t dh6opt_len;
/* type-dependent data follows */
};
static const char *
dhcp6stcode(const uint16_t code)
{
return code > 255 ? "INVALID code" : tok2str(dh6opt_stcode_str, "code%u", code);
}
static void
dhcp6opt_print(netdissect_options *ndo,
const u_char *cp, const u_char *ep)
{
const struct dhcp6opt *dh6o;
const u_char *tp;
size_t i;
uint16_t opttype;
size_t optlen;
uint8_t auth_proto;
u_int authinfolen, authrealmlen;
int remain_len; /* Length of remaining options */
int label_len; /* Label length */
uint16_t subopt_code;
uint16_t subopt_len;
if (cp == ep)
return;
while (cp < ep) {
if (ep < cp + sizeof(*dh6o))
goto trunc;
dh6o = (const struct dhcp6opt *)cp;
ND_TCHECK(*dh6o);
optlen = EXTRACT_16BITS(&dh6o->dh6opt_len);
if (ep < cp + sizeof(*dh6o) + optlen)
goto trunc;
opttype = EXTRACT_16BITS(&dh6o->dh6opt_type);
ND_PRINT((ndo, " (%s", tok2str(dh6opt_str, "opt_%u", opttype)));
ND_TCHECK2(*(cp + sizeof(*dh6o)), optlen);
switch (opttype) {
case DH6OPT_CLIENTID:
case DH6OPT_SERVERID:
if (optlen < 2) {
/*(*/
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
switch (EXTRACT_16BITS(tp)) {
case 1:
if (optlen >= 2 + 6) {
ND_PRINT((ndo, " hwaddr/time type %u time %u ",
EXTRACT_16BITS(&tp[2]),
EXTRACT_32BITS(&tp[4])));
for (i = 8; i < optlen; i++)
ND_PRINT((ndo, "%02x", tp[i]));
/*(*/
ND_PRINT((ndo, ")"));
} else {
/*(*/
ND_PRINT((ndo, " ?)"));
}
break;
case 2:
if (optlen >= 2 + 8) {
ND_PRINT((ndo, " vid "));
for (i = 2; i < 2 + 8; i++)
ND_PRINT((ndo, "%02x", tp[i]));
/*(*/
ND_PRINT((ndo, ")"));
} else {
/*(*/
ND_PRINT((ndo, " ?)"));
}
break;
case 3:
if (optlen >= 2 + 2) {
ND_PRINT((ndo, " hwaddr type %u ",
EXTRACT_16BITS(&tp[2])));
for (i = 4; i < optlen; i++)
ND_PRINT((ndo, "%02x", tp[i]));
/*(*/
ND_PRINT((ndo, ")"));
} else {
/*(*/
ND_PRINT((ndo, " ?)"));
}
break;
default:
ND_PRINT((ndo, " type %d)", EXTRACT_16BITS(tp)));
break;
}
break;
case DH6OPT_IA_ADDR:
if (optlen < 24) {
/*(*/
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[0])));
ND_PRINT((ndo, " pltime:%u vltime:%u",
EXTRACT_32BITS(&tp[16]),
EXTRACT_32BITS(&tp[20])));
if (optlen > 24) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 24, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_ORO:
case DH6OPT_ERO:
if (optlen % 2) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
for (i = 0; i < optlen; i += 2) {
ND_PRINT((ndo, " %s",
tok2str(dh6opt_str, "opt_%u", EXTRACT_16BITS(&tp[i]))));
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_PREFERENCE:
if (optlen != 1) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d)", *tp));
break;
case DH6OPT_ELAPSED_TIME:
if (optlen != 2) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d)", EXTRACT_16BITS(tp)));
break;
case DH6OPT_RELAY_MSG:
ND_PRINT((ndo, " ("));
tp = (const u_char *)(dh6o + 1);
dhcp6_print(ndo, tp, optlen);
ND_PRINT((ndo, ")"));
break;
case DH6OPT_AUTH:
if (optlen < 11) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
auth_proto = *tp;
switch (auth_proto) {
case DH6OPT_AUTHPROTO_DELAYED:
ND_PRINT((ndo, " proto: delayed"));
break;
case DH6OPT_AUTHPROTO_RECONFIG:
ND_PRINT((ndo, " proto: reconfigure"));
break;
default:
ND_PRINT((ndo, " proto: %d", auth_proto));
break;
}
tp++;
switch (*tp) {
case DH6OPT_AUTHALG_HMACMD5:
/* XXX: may depend on the protocol */
ND_PRINT((ndo, ", alg: HMAC-MD5"));
break;
default:
ND_PRINT((ndo, ", alg: %d", *tp));
break;
}
tp++;
switch (*tp) {
case DH6OPT_AUTHRDM_MONOCOUNTER:
ND_PRINT((ndo, ", RDM: mono"));
break;
default:
ND_PRINT((ndo, ", RDM: %d", *tp));
break;
}
tp++;
ND_PRINT((ndo, ", RD:"));
for (i = 0; i < 4; i++, tp += 2)
ND_PRINT((ndo, " %04x", EXTRACT_16BITS(tp)));
/* protocol dependent part */
authinfolen = optlen - 11;
switch (auth_proto) {
case DH6OPT_AUTHPROTO_DELAYED:
if (authinfolen == 0)
break;
if (authinfolen < 20) {
ND_PRINT((ndo, " ??"));
break;
}
authrealmlen = authinfolen - 20;
if (authrealmlen > 0) {
ND_PRINT((ndo, ", realm: "));
}
for (i = 0; i < authrealmlen; i++, tp++)
ND_PRINT((ndo, "%02x", *tp));
ND_PRINT((ndo, ", key ID: %08x", EXTRACT_32BITS(tp)));
tp += 4;
ND_PRINT((ndo, ", HMAC-MD5:"));
for (i = 0; i < 4; i++, tp+= 4)
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tp)));
break;
case DH6OPT_AUTHPROTO_RECONFIG:
if (authinfolen != 17) {
ND_PRINT((ndo, " ??"));
break;
}
switch (*tp++) {
case DH6OPT_AUTHRECONFIG_KEY:
ND_PRINT((ndo, " reconfig-key"));
break;
case DH6OPT_AUTHRECONFIG_HMACMD5:
ND_PRINT((ndo, " type: HMAC-MD5"));
break;
default:
ND_PRINT((ndo, " type: ??"));
break;
}
ND_PRINT((ndo, " value:"));
for (i = 0; i < 4; i++, tp+= 4)
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tp)));
break;
default:
ND_PRINT((ndo, " ??"));
break;
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_RAPID_COMMIT: /* nothing todo */
ND_PRINT((ndo, ")"));
break;
case DH6OPT_INTERFACE_ID:
case DH6OPT_SUBSCRIBER_ID:
/*
* Since we cannot predict the encoding, print hex dump
* at most 10 characters.
*/
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " "));
for (i = 0; i < optlen && i < 10; i++)
ND_PRINT((ndo, "%02x", tp[i]));
ND_PRINT((ndo, "...)"));
break;
case DH6OPT_RECONF_MSG:
if (optlen != 1) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
switch (*tp) {
case DH6_RENEW:
ND_PRINT((ndo, " for renew)"));
break;
case DH6_INFORM_REQ:
ND_PRINT((ndo, " for inf-req)"));
break;
default:
ND_PRINT((ndo, " for ?\?\?(%02x))", *tp));
break;
}
break;
case DH6OPT_RECONF_ACCEPT: /* nothing todo */
ND_PRINT((ndo, ")"));
break;
case DH6OPT_SIP_SERVER_A:
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS:
case DH6OPT_NIS_SERVERS:
case DH6OPT_NISP_SERVERS:
case DH6OPT_BCMCS_SERVER_A:
case DH6OPT_PANA_AGENT:
case DH6OPT_LQ_CLIENT_LINK:
if (optlen % 16) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
for (i = 0; i < optlen; i += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[i])));
ND_PRINT((ndo, ")"));
break;
case DH6OPT_SIP_SERVER_D:
case DH6OPT_DOMAIN_LIST:
tp = (const u_char *)(dh6o + 1);
while (tp < cp + sizeof(*dh6o) + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, cp + sizeof(*dh6o) + optlen)) == NULL)
goto trunc;
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_STATUS_CODE:
if (optlen < 2) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s)", dhcp6stcode(EXTRACT_16BITS(&tp[0]))));
break;
case DH6OPT_IA_NA:
case DH6OPT_IA_PD:
if (optlen < 12) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " IAID:%u T1:%u T2:%u",
EXTRACT_32BITS(&tp[0]),
EXTRACT_32BITS(&tp[4]),
EXTRACT_32BITS(&tp[8])));
if (optlen > 12) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 12, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_IA_TA:
if (optlen < 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " IAID:%u", EXTRACT_32BITS(tp)));
if (optlen > 4) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 4, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_IA_PD_PREFIX:
if (optlen < 25) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s/%d", ip6addr_string(ndo, &tp[9]), tp[8]));
ND_PRINT((ndo, " pltime:%u vltime:%u",
EXTRACT_32BITS(&tp[0]),
EXTRACT_32BITS(&tp[4])));
if (optlen > 25) {
/* there are sub-options */
dhcp6opt_print(ndo, tp + 25, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_LIFETIME:
case DH6OPT_CLT_TIME:
if (optlen != 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d)", EXTRACT_32BITS(tp)));
break;
case DH6OPT_REMOTE_ID:
if (optlen < 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %d ", EXTRACT_32BITS(tp)));
/*
* Print hex dump first 10 characters.
*/
for (i = 4; i < optlen && i < 14; i++)
ND_PRINT((ndo, "%02x", tp[i]));
ND_PRINT((ndo, "...)"));
break;
case DH6OPT_LQ_QUERY:
if (optlen < 17) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
switch (*tp) {
case 1:
ND_PRINT((ndo, " by-address"));
break;
case 2:
ND_PRINT((ndo, " by-clientID"));
break;
default:
ND_PRINT((ndo, " type_%d", (int)*tp));
break;
}
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[1])));
if (optlen > 17) {
/* there are query-options */
dhcp6opt_print(ndo, tp + 17, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_CLIENT_DATA:
tp = (const u_char *)(dh6o + 1);
if (optlen > 0) {
/* there are encapsulated options */
dhcp6opt_print(ndo, tp, tp + optlen);
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_LQ_RELAY_DATA:
if (optlen < 16) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, " %s ", ip6addr_string(ndo, &tp[0])));
/*
* Print hex dump first 10 characters.
*/
for (i = 16; i < optlen && i < 26; i++)
ND_PRINT((ndo, "%02x", tp[i]));
ND_PRINT((ndo, "...)"));
break;
case DH6OPT_NTP_SERVER:
if (optlen < 4) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
while (tp < cp + sizeof(*dh6o) + optlen - 4) {
subopt_code = EXTRACT_16BITS(tp);
tp += 2;
subopt_len = EXTRACT_16BITS(tp);
tp += 2;
if (tp + subopt_len > cp + sizeof(*dh6o) + optlen)
goto trunc;
ND_PRINT((ndo, " subopt:%d", subopt_code));
switch (subopt_code) {
case DH6OPT_NTP_SUBOPTION_SRV_ADDR:
case DH6OPT_NTP_SUBOPTION_MC_ADDR:
if (subopt_len != 16) {
ND_PRINT((ndo, " ?"));
break;
}
ND_PRINT((ndo, " %s", ip6addr_string(ndo, &tp[0])));
break;
case DH6OPT_NTP_SUBOPTION_SRV_FQDN:
ND_PRINT((ndo, " "));
if (ns_nprint(ndo, tp, tp + subopt_len) == NULL)
goto trunc;
break;
default:
ND_PRINT((ndo, " ?"));
break;
}
tp += subopt_len;
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_AFTR_NAME:
if (optlen < 3) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
remain_len = optlen;
ND_PRINT((ndo, " "));
/* Encoding is described in section 3.1 of RFC 1035 */
while (remain_len && *tp) {
label_len = *tp++;
if (label_len < remain_len - 1) {
(void)fn_printn(ndo, tp, label_len, NULL);
tp += label_len;
remain_len -= (label_len + 1);
if(*tp) ND_PRINT((ndo, "."));
} else {
ND_PRINT((ndo, " ?"));
break;
}
}
ND_PRINT((ndo, ")"));
break;
case DH6OPT_NEW_POSIX_TIMEZONE: /* all three of these options */
case DH6OPT_NEW_TZDB_TIMEZONE: /* are encoded similarly */
case DH6OPT_MUDURL: /* although GMT might not work */
if (optlen < 5) {
ND_PRINT((ndo, " ?)"));
break;
}
tp = (const u_char *)(dh6o + 1);
ND_PRINT((ndo, "="));
(void)fn_printn(ndo, tp, (u_int)optlen, NULL);
ND_PRINT((ndo, ")"));
break;
default:
ND_PRINT((ndo, ")"));
break;
}
cp += sizeof(*dh6o) + optlen;
}
return;
trunc:
ND_PRINT((ndo, "[|dhcp6ext]"));
}
/*
* Print dhcp6 packets
*/
void
dhcp6_print(netdissect_options *ndo,
const u_char *cp, u_int length)
{
const struct dhcp6 *dh6;
const struct dhcp6_relay *dh6relay;
const u_char *ep;
const u_char *extp;
const char *name;
ND_PRINT((ndo, "dhcp6"));
ep = (const u_char *)ndo->ndo_snapend;
if (cp + length < ep)
ep = cp + length;
dh6 = (const struct dhcp6 *)cp;
dh6relay = (const struct dhcp6_relay *)cp;
ND_TCHECK(dh6->dh6_xid);
name = tok2str(dh6_msgtype_str, "msgtype-%u", dh6->dh6_msgtype);
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, " %s", name));
return;
}
/* XXX relay agent messages have to be handled differently */
ND_PRINT((ndo, " %s (", name)); /*)*/
if (dh6->dh6_msgtype != DH6_RELAY_FORW &&
dh6->dh6_msgtype != DH6_RELAY_REPLY) {
ND_PRINT((ndo, "xid=%x", EXTRACT_32BITS(&dh6->dh6_xid) & DH6_XIDMASK));
extp = (const u_char *)(dh6 + 1);
dhcp6opt_print(ndo, extp, ep);
} else { /* relay messages */
struct in6_addr addr6;
ND_TCHECK(dh6relay->dh6relay_peeraddr);
memcpy(&addr6, dh6relay->dh6relay_linkaddr, sizeof (addr6));
ND_PRINT((ndo, "linkaddr=%s", ip6addr_string(ndo, &addr6)));
memcpy(&addr6, dh6relay->dh6relay_peeraddr, sizeof (addr6));
ND_PRINT((ndo, " peeraddr=%s", ip6addr_string(ndo, &addr6)));
dhcp6opt_print(ndo, (const u_char *)(dh6relay + 1), ep);
}
/*(*/
ND_PRINT((ndo, ")"));
return;
trunc:
ND_PRINT((ndo, "[|dhcp6]"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2692_0 |
crossvul-cpp_data_bad_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 (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/bad_3394_0 |
crossvul-cpp_data_bad_5308_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X X CCCC FFFFF %
% X X C F %
% X C FFF %
% X X C F %
% X X CCCC F %
% %
% %
% Read GIMP XCF Image Format %
% %
% Software Design %
% Leonard Rosenthol %
% November 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/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/composite.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/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Typedef declarations.
*/
typedef enum
{
GIMP_RGB,
GIMP_GRAY,
GIMP_INDEXED
} GimpImageBaseType;
typedef enum
{
PROP_END = 0,
PROP_COLORMAP = 1,
PROP_ACTIVE_LAYER = 2,
PROP_ACTIVE_CHANNEL = 3,
PROP_SELECTION = 4,
PROP_FLOATING_SELECTION = 5,
PROP_OPACITY = 6,
PROP_MODE = 7,
PROP_VISIBLE = 8,
PROP_LINKED = 9,
PROP_PRESERVE_TRANSPARENCY = 10,
PROP_APPLY_MASK = 11,
PROP_EDIT_MASK = 12,
PROP_SHOW_MASK = 13,
PROP_SHOW_MASKED = 14,
PROP_OFFSETS = 15,
PROP_COLOR = 16,
PROP_COMPRESSION = 17,
PROP_GUIDES = 18,
PROP_RESOLUTION = 19,
PROP_TATTOO = 20,
PROP_PARASITES = 21,
PROP_UNIT = 22,
PROP_PATHS = 23,
PROP_USER_UNIT = 24
} PropType;
typedef enum
{
COMPRESS_NONE = 0,
COMPRESS_RLE = 1,
COMPRESS_ZLIB = 2, /* unused */
COMPRESS_FRACTAL = 3 /* unused */
} XcfCompressionType;
typedef struct
{
size_t
width,
height,
image_type,
bytes_per_pixel;
int
compression;
size_t
file_size;
size_t
number_layers;
} XCFDocInfo;
typedef struct
{
char
name[1024];
unsigned int
active;
size_t
width,
height,
type,
alpha,
visible,
linked,
preserve_trans,
apply_mask,
show_mask,
edit_mask,
floating_offset;
ssize_t
offset_x,
offset_y;
size_t
mode,
tattoo;
Image
*image;
} XCFLayerInfo;
#define TILE_WIDTH 64
#define TILE_HEIGHT 64
typedef struct
{
unsigned char
red,
green,
blue,
alpha;
} XCFPixelInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s X C F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsXCF() returns MagickTrue if the image format type, identified by the
% magick string, is XCF (GIMP native format).
%
% The format of the IsXCF method is:
%
% MagickBooleanType IsXCF(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 IsXCF(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"gimp xcf",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
typedef enum
{
GIMP_NORMAL_MODE,
GIMP_DISSOLVE_MODE,
GIMP_BEHIND_MODE,
GIMP_MULTIPLY_MODE,
GIMP_SCREEN_MODE,
GIMP_OVERLAY_MODE,
GIMP_DIFFERENCE_MODE,
GIMP_ADDITION_MODE,
GIMP_SUBTRACT_MODE,
GIMP_DARKEN_ONLY_MODE,
GIMP_LIGHTEN_ONLY_MODE,
GIMP_HUE_MODE,
GIMP_SATURATION_MODE,
GIMP_COLOR_MODE,
GIMP_VALUE_MODE,
GIMP_DIVIDE_MODE,
GIMP_DODGE_MODE,
GIMP_BURN_MODE,
GIMP_HARDLIGHT_MODE
} GimpLayerModeEffects;
/*
Simple utility routine to convert between PSD blending modes and
ImageMagick compositing operators
*/
static CompositeOperator GIMPBlendModeToCompositeOperator(
size_t blendMode)
{
switch ( blendMode )
{
case GIMP_NORMAL_MODE: return(OverCompositeOp);
case GIMP_DISSOLVE_MODE: return(DissolveCompositeOp);
case GIMP_MULTIPLY_MODE: return(MultiplyCompositeOp);
case GIMP_SCREEN_MODE: return(ScreenCompositeOp);
case GIMP_OVERLAY_MODE: return(OverlayCompositeOp);
case GIMP_DIFFERENCE_MODE: return(DifferenceCompositeOp);
case GIMP_ADDITION_MODE: return(ModulusAddCompositeOp);
case GIMP_SUBTRACT_MODE: return(ModulusSubtractCompositeOp);
case GIMP_DARKEN_ONLY_MODE: return(DarkenCompositeOp);
case GIMP_LIGHTEN_ONLY_MODE: return(LightenCompositeOp);
case GIMP_HUE_MODE: return(HueCompositeOp);
case GIMP_SATURATION_MODE: return(SaturateCompositeOp);
case GIMP_COLOR_MODE: return(ColorizeCompositeOp);
case GIMP_DODGE_MODE: return(ColorDodgeCompositeOp);
case GIMP_BURN_MODE: return(ColorBurnCompositeOp);
case GIMP_HARDLIGHT_MODE: return(HardLightCompositeOp);
case GIMP_DIVIDE_MODE: return(DivideDstCompositeOp);
/* these are the ones we don't support...yet */
case GIMP_BEHIND_MODE: return(OverCompositeOp);
case GIMP_VALUE_MODE: return(OverCompositeOp);
default: return(OverCompositeOp);
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d B l o b S t r i n g W i t h L o n g S i z e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadBlobStringWithLongSize reads characters from a blob or file
% starting with a ssize_t length byte and then characters to that length
%
% The format of the ReadBlobStringWithLongSize method is:
%
% char *ReadBlobStringWithLongSize(Image *image,char *string)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o string: the address of a character buffer.
%
*/
static char *ReadBlobStringWithLongSize(Image *image,char *string,size_t max,
ExceptionInfo *exception)
{
int
c;
MagickOffsetType
offset;
register ssize_t
i;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(max != 0);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=ReadBlobMSBLong(image);
for (i=0; i < (ssize_t) MagickMin(length,max-1); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
return((char *) NULL);
string[i]=(char) c;
}
string[i]='\0';
offset=SeekBlob(image,(MagickOffsetType) (length-i),SEEK_CUR);
if (offset < 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"ImproperImageHeader","`%s'",image->filename);
return(string);
}
static MagickBooleanType load_tile(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,
ExceptionInfo *exception)
{
ssize_t
y;
register ssize_t
x;
register Quantum
*q;
ssize_t
count;
unsigned char
*graydata;
XCFPixelInfo
*xcfdata,
*xcfodata;
xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));
if (xcfdata == (XCFPixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
graydata=(unsigned char *) xcfdata; /* used by gray and indexed */
count=ReadBlob(image,data_length,(unsigned char *) xcfdata);
if (count != (ssize_t) data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (inDocInfo->image_type == GIMP_GRAY)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q);
SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char)
inLayerInfo->alpha),q);
graydata++;
q+=GetPixelChannels(tile_image);
}
}
else
if (inDocInfo->image_type == GIMP_RGB)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q);
SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha :
ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q);
xcfdata++;
q+=GetPixelChannels(tile_image);
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata);
return MagickTrue;
}
static MagickBooleanType load_tile_rle(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,
ExceptionInfo *exception)
{
MagickOffsetType
size;
Quantum
alpha;
register Quantum
*q;
size_t
length;
ssize_t
bytes_per_pixel,
count,
i,
j;
unsigned char
data,
pixel,
*xcfdata,
*xcfodata,
*xcfdatalimit;
bytes_per_pixel=(ssize_t) inDocInfo->bytes_per_pixel;
xcfdata=(unsigned char *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));
if (xcfdata == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
count=ReadBlob(image, (size_t) data_length, xcfdata);
xcfdatalimit = xcfodata+count-1;
alpha=ScaleCharToQuantum((unsigned char) inLayerInfo->alpha);
for (i=0; i < (ssize_t) bytes_per_pixel; i++)
{
q=GetAuthenticPixels(tile_image,0,0,tile_image->columns,tile_image->rows,
exception);
if (q == (Quantum *) NULL)
continue;
size=(MagickOffsetType) tile_image->rows*tile_image->columns;
while (size > 0)
{
if (xcfdata > xcfdatalimit)
goto bogus_rle;
pixel=(*xcfdata++);
length=(size_t) pixel;
if (length >= 128)
{
length=255-(length-1);
if (length == 128)
{
if (xcfdata >= xcfdatalimit)
goto bogus_rle;
length=(size_t) ((*xcfdata << 8) + xcfdata[1]);
xcfdata+=2;
}
size-=length;
if (size < 0)
goto bogus_rle;
if (&xcfdata[length-1] > xcfdatalimit)
goto bogus_rle;
while (length-- > 0)
{
data=(*xcfdata++);
switch (i)
{
case 0:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelGray(tile_image,ScaleCharToQuantum(data),q);
else
{
SetPixelRed(tile_image,ScaleCharToQuantum(data),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(data),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(data),q);
}
SetPixelAlpha(tile_image,alpha,q);
break;
}
case 1:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelAlpha(tile_image,ScaleCharToQuantum(data),q);
else
SetPixelGreen(tile_image,ScaleCharToQuantum(data),q);
break;
}
case 2:
{
SetPixelBlue(tile_image,ScaleCharToQuantum(data),q);
break;
}
case 3:
{
SetPixelAlpha(tile_image,ScaleCharToQuantum(data),q);
break;
}
}
q+=GetPixelChannels(tile_image);
}
}
else
{
length+=1;
if (length == 128)
{
if (xcfdata >= xcfdatalimit)
goto bogus_rle;
length=(size_t) ((*xcfdata << 8) + xcfdata[1]);
xcfdata+=2;
}
size-=length;
if (size < 0)
goto bogus_rle;
if (xcfdata > xcfdatalimit)
goto bogus_rle;
pixel=(*xcfdata++);
for (j=0; j < (ssize_t) length; j++)
{
data=pixel;
switch (i)
{
case 0:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelGray(tile_image,ScaleCharToQuantum(data),q);
else
{
SetPixelRed(tile_image,ScaleCharToQuantum(data),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(data),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(data),q);
}
SetPixelAlpha(tile_image,alpha,q);
break;
}
case 1:
{
if (inDocInfo->image_type == GIMP_GRAY)
SetPixelAlpha(tile_image,ScaleCharToQuantum(data),q);
else
SetPixelGreen(tile_image,ScaleCharToQuantum(data),q);
break;
}
case 2:
{
SetPixelBlue(tile_image,ScaleCharToQuantum(data),q);
break;
}
case 3:
{
SetPixelAlpha(tile_image,ScaleCharToQuantum(data),q);
break;
}
}
q+=GetPixelChannels(tile_image);
}
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(unsigned char *) RelinquishMagickMemory(xcfodata);
return(MagickTrue);
bogus_rle:
if (xcfodata != (unsigned char *) NULL)
xcfodata=(unsigned char *) RelinquishMagickMemory(xcfodata);
return(MagickFalse);
}
static MagickBooleanType load_level(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayerInfo,ExceptionInfo *exception)
{
int
destLeft = 0,
destTop = 0;
Image*
tile_image;
MagickBooleanType
status;
MagickOffsetType
saved_pos,
offset,
offset2;
register ssize_t
i;
size_t
width,
height,
ntiles,
ntile_rows,
ntile_cols,
tile_image_width,
tile_image_height;
/* start reading the data */
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
/* read in the first tile offset.
* if it is '0', then this tile level is empty
* and we can simply return.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image);
if (offset == 0)
return(MagickTrue);
/* Initialise the reference for the in-memory tile-compression
*/
ntile_rows=(height+TILE_HEIGHT-1)/TILE_HEIGHT;
ntile_cols=(width+TILE_WIDTH-1)/TILE_WIDTH;
ntiles=ntile_rows*ntile_cols;
for (i = 0; i < (ssize_t) ntiles; i++)
{
status=MagickFalse;
if (offset == 0)
ThrowBinaryException(CorruptImageError,"NotEnoughTiles",image->filename);
/* save the current position as it is where the
* next tile offset is stored.
*/
saved_pos=TellBlob(image);
/* read in the offset of the next tile so we can calculate the amount
of data needed for this tile*/
offset2=(MagickOffsetType)ReadBlobMSBLong(image);
/* if the offset is 0 then we need to read in the maximum possible
allowing for negative compression */
if (offset2 == 0)
offset2=(MagickOffsetType) (offset + TILE_WIDTH * TILE_WIDTH * 4* 1.5);
/* seek to the tile offset */
offset=SeekBlob(image, offset, SEEK_SET);
/*
Allocate the image for the tile. NOTE: the last tile in a row or
column may not be a full tile!
*/
tile_image_width=(size_t) (destLeft == (int) ntile_cols-1 ?
(int) width % TILE_WIDTH : TILE_WIDTH);
if (tile_image_width == 0)
tile_image_width=TILE_WIDTH;
tile_image_height = (size_t) (destTop == (int) ntile_rows-1 ?
(int) height % TILE_HEIGHT : TILE_HEIGHT);
if (tile_image_height == 0)
tile_image_height=TILE_HEIGHT;
tile_image=CloneImage(inLayerInfo->image,tile_image_width,
tile_image_height,MagickTrue,exception);
/* read in the tile */
switch (inDocInfo->compression)
{
case COMPRESS_NONE:
if (load_tile(image,tile_image,inDocInfo,inLayerInfo,(size_t) (offset2-offset),exception) == 0)
status=MagickTrue;
break;
case COMPRESS_RLE:
if (load_tile_rle (image,tile_image,inDocInfo,inLayerInfo,
(int) (offset2-offset),exception) == 0)
status=MagickTrue;
break;
case COMPRESS_ZLIB:
ThrowBinaryException(CoderError,"ZipCompressNotSupported",
image->filename)
case COMPRESS_FRACTAL:
ThrowBinaryException(CoderError,"FractalCompressNotSupported",
image->filename)
}
/* composite the tile onto the layer's image, and then destroy it */
(void) CompositeImage(inLayerInfo->image,tile_image,CopyCompositeOp,
MagickTrue,destLeft * TILE_WIDTH,destTop*TILE_HEIGHT,exception);
tile_image=DestroyImage(tile_image);
/* adjust tile position */
destLeft++;
if (destLeft >= (int) ntile_cols)
{
destLeft = 0;
destTop++;
}
if (status != MagickFalse)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
/* read in the offset of the next tile */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
}
if (offset != 0)
ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename)
return(MagickTrue);
}
static MagickBooleanType load_hierarchy(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayer, ExceptionInfo *exception)
{
MagickOffsetType
saved_pos,
offset,
junk;
size_t
width,
height,
bytes_per_pixel;
width=ReadBlobMSBLong(image);
(void) width;
height=ReadBlobMSBLong(image);
(void) height;
bytes_per_pixel=inDocInfo->bytes_per_pixel=ReadBlobMSBLong(image);
(void) bytes_per_pixel;
/* load in the levels...we make sure that the number of levels
* calculated when the TileManager was created is the same
* as the number of levels found in the file.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image); /* top level */
/* discard offsets for layers below first, if any.
*/
do
{
junk=(MagickOffsetType) ReadBlobMSBLong(image);
}
while (junk != 0);
/* save the current position as it is where the
* next level offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the level offset */
offset=SeekBlob(image, offset, SEEK_SET);
/* read in the level */
if (load_level (image, inDocInfo, inLayer, exception) == 0)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
return(MagickTrue);
}
static void InitXCFImage(XCFLayerInfo *outLayer,ExceptionInfo *exception)
{
outLayer->image->page.x=outLayer->offset_x;
outLayer->image->page.y=outLayer->offset_y;
outLayer->image->page.width=outLayer->width;
outLayer->image->page.height=outLayer->height;
(void) SetImageProperty(outLayer->image,"label",(char *)outLayer->name,
exception);
}
static MagickBooleanType ReadOneLayer(const ImageInfo *image_info,Image* image,
XCFDocInfo* inDocInfo,XCFLayerInfo *outLayer,const ssize_t layer,
ExceptionInfo *exception)
{
MagickOffsetType
offset;
unsigned int
foundPropEnd = 0;
size_t
hierarchy_offset,
layer_mask_offset;
/* clear the block! */
(void) ResetMagickMemory( outLayer, 0, sizeof( XCFLayerInfo ) );
/* read in the layer width, height, type and name */
outLayer->width = ReadBlobMSBLong(image);
outLayer->height = ReadBlobMSBLong(image);
outLayer->type = ReadBlobMSBLong(image);
(void) ReadBlobStringWithLongSize(image, outLayer->name,
sizeof(outLayer->name),exception);
/* read the layer properties! */
foundPropEnd = 0;
while ( (foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse) ) {
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd = 1;
break;
case PROP_ACTIVE_LAYER:
outLayer->active = 1;
break;
case PROP_FLOATING_SELECTION:
outLayer->floating_offset = ReadBlobMSBLong(image);
break;
case PROP_OPACITY:
outLayer->alpha = ReadBlobMSBLong(image);
break;
case PROP_VISIBLE:
outLayer->visible = ReadBlobMSBLong(image);
break;
case PROP_LINKED:
outLayer->linked = ReadBlobMSBLong(image);
break;
case PROP_PRESERVE_TRANSPARENCY:
outLayer->preserve_trans = ReadBlobMSBLong(image);
break;
case PROP_APPLY_MASK:
outLayer->apply_mask = ReadBlobMSBLong(image);
break;
case PROP_EDIT_MASK:
outLayer->edit_mask = ReadBlobMSBLong(image);
break;
case PROP_SHOW_MASK:
outLayer->show_mask = ReadBlobMSBLong(image);
break;
case PROP_OFFSETS:
outLayer->offset_x = (int) ReadBlobMSBLong(image);
outLayer->offset_y = (int) ReadBlobMSBLong(image);
break;
case PROP_MODE:
outLayer->mode = ReadBlobMSBLong(image);
break;
case PROP_TATTOO:
outLayer->preserve_trans = ReadBlobMSBLong(image);
break;
case PROP_PARASITES:
{
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
ssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite(info);
gimp_drawable_parasite_attach(GIMP_DRAWABLE(layer), p);
gimp_parasite_free(p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading a layer's parasites");
*/
}
break;
default:
/* g_message ("unexpected/unknown layer property: %d (skipping)",
prop_type); */
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount = (ssize_t) MagickMin(16, prop_size);
amount = ReadBlob(image, (size_t) amount, (unsigned char *) &buf);
if (!amount)
ThrowBinaryException(CorruptImageError,"CorruptImage",
image->filename);
prop_size -= (size_t) MagickMin(16, (size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
return(MagickFalse);
/* allocate the image for this layer */
if (image_info->number_scenes != 0)
{
ssize_t
scene;
scene=inDocInfo->number_layers-layer-1;
if (scene > (ssize_t) (image_info->scene+image_info->number_scenes-1))
{
outLayer->image=CloneImage(image,0,0,MagickTrue,exception);
if (outLayer->image == (Image *) NULL)
return(MagickFalse);
InitXCFImage(outLayer,exception);
return(MagickTrue);
}
}
outLayer->image=CloneImage(image,outLayer->width, outLayer->height,MagickTrue,
exception);
if (outLayer->image == (Image *) NULL)
return(MagickFalse);
/* clear the image based on the layer opacity */
outLayer->image->background_color.alpha=
ScaleCharToQuantum((unsigned char) outLayer->alpha);
(void) SetImageBackgroundColor(outLayer->image,exception);
InitXCFImage(outLayer,exception);
/* set the compositing mode */
outLayer->image->compose = GIMPBlendModeToCompositeOperator( outLayer->mode );
if ( outLayer->visible == MagickFalse )
{
/* BOGUS: should really be separate member var! */
outLayer->image->compose = NoCompositeOp;
}
/* read the hierarchy and layer mask offsets */
hierarchy_offset = ReadBlobMSBLong(image);
layer_mask_offset = ReadBlobMSBLong(image);
/* read in the hierarchy */
offset=SeekBlob(image, (MagickOffsetType) hierarchy_offset, SEEK_SET);
if (offset < 0)
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InvalidImageHeader","`%s'",image->filename);
if (load_hierarchy (image, inDocInfo, outLayer, exception) == 0)
return(MagickFalse);
/* read in the layer mask */
if (layer_mask_offset != 0)
{
offset=SeekBlob(image, (MagickOffsetType) layer_mask_offset, SEEK_SET);
#if 0 /* BOGUS: support layer masks! */
layer_mask = xcf_load_layer_mask (info, gimage);
if (layer_mask == 0)
goto error;
/* set the offsets of the layer_mask */
GIMP_DRAWABLE (layer_mask)->offset_x = GIMP_DRAWABLE (layer)->offset_x;
GIMP_DRAWABLE (layer_mask)->offset_y = GIMP_DRAWABLE (layer)->offset_y;
gimp_layer_add_mask (layer, layer_mask, MagickFalse);
layer->mask->apply_mask = apply_mask;
layer->mask->edit_mask = edit_mask;
layer->mask->show_mask = show_mask;
#endif
}
/* attach the floating selection... */
#if 0 /* BOGUS: we may need to read this, even if we don't support it! */
if (add_floating_sel)
{
GimpLayer *floating_sel;
floating_sel = info->floating_sel;
floating_sel_attach (floating_sel, GIMP_DRAWABLE (layer));
}
#endif
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadXCFImage() reads a GIMP (GNU Image Manipulation Program) 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 ReadXCFImage method is:
%
% image=ReadXCFImage(image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadXCFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[14];
Image
*image;
int
foundPropEnd = 0;
MagickBooleanType
status;
MagickOffsetType
offset;
register ssize_t
i;
size_t
image_type,
length;
ssize_t
count;
XCFDocInfo
doc_info;
/*
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);
}
count=ReadBlob(image,14,(unsigned char *) magick);
if ((count != 14) ||
(LocaleNCompare((char *) magick,"gimp xcf",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ResetMagickMemory(&doc_info,0,sizeof(XCFDocInfo));
doc_info.width=ReadBlobMSBLong(image);
doc_info.height=ReadBlobMSBLong(image);
if ((doc_info.width > 262144) || (doc_info.height > 262144))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
doc_info.image_type=ReadBlobMSBLong(image);
/*
Initialize image attributes.
*/
image->columns=doc_info.width;
image->rows=doc_info.height;
image_type=doc_info.image_type;
doc_info.file_size=GetBlobSize(image);
image->compression=NoCompression;
image->depth=8;
if (image_type == GIMP_RGB)
SetImageColorspace(image,sRGBColorspace,exception);
else
if (image_type == GIMP_GRAY)
SetImageColorspace(image,GRAYColorspace,exception);
else
if (image_type == GIMP_INDEXED)
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
(void) SetImageBackgroundColor(image,exception);
(void) SetImageAlpha(image,OpaqueAlpha,exception);
/*
Read properties.
*/
while ((foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse))
{
PropType prop_type = (PropType) ReadBlobMSBLong(image);
size_t prop_size = ReadBlobMSBLong(image);
switch (prop_type)
{
case PROP_END:
foundPropEnd=1;
break;
case PROP_COLORMAP:
{
/* Cannot rely on prop_size here--the value is set incorrectly
by some Gimp versions.
*/
size_t num_colours = ReadBlobMSBLong(image);
if (DiscardBlobBytes(image,3*num_colours) == MagickFalse)
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
if (info->file_version == 0)
{
gint i;
g_message (_("XCF warning: version 0 of XCF file format\n"
"did not save indexed colormaps correctly.\n"
"Substituting grayscale map."));
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
xcf_seek_pos (info, info->cp + gimage->num_cols);
for (i = 0; i<gimage->num_cols; i++)
{
gimage->cmap[i*3+0] = i;
gimage->cmap[i*3+1] = i;
gimage->cmap[i*3+2] = i;
}
}
else
{
info->cp +=
xcf_read_int32 (info->fp, (guint32*) &gimage->num_cols, 1);
gimage->cmap = g_new (guchar, gimage->num_cols*3);
info->cp +=
xcf_read_int8 (info->fp,
(guint8*) gimage->cmap, gimage->num_cols*3);
}
*/
break;
}
case PROP_COMPRESSION:
{
doc_info.compression = ReadBlobByte(image);
if ((doc_info.compression != COMPRESS_NONE) &&
(doc_info.compression != COMPRESS_RLE) &&
(doc_info.compression != COMPRESS_ZLIB) &&
(doc_info.compression != COMPRESS_FRACTAL))
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
break;
case PROP_GUIDES:
{
/* just skip it - we don't care about guides */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
break;
case PROP_RESOLUTION:
{
/* float xres = (float) */ (void) ReadBlobMSBLong(image);
/* float yres = (float) */ (void) ReadBlobMSBLong(image);
/*
if (xres < GIMP_MIN_RESOLUTION || xres > GIMP_MAX_RESOLUTION ||
yres < GIMP_MIN_RESOLUTION || yres > GIMP_MAX_RESOLUTION)
{
g_message ("Warning, resolution out of range in XCF file");
xres = gimage->gimp->config->default_xresolution;
yres = gimage->gimp->config->default_yresolution;
}
*/
/* BOGUS: we don't write these yet because we aren't
reading them properly yet :(
image->resolution.x = xres;
image->resolution.y = yres;
*/
}
break;
case PROP_TATTOO:
{
/* we need to read it, even if we ignore it */
/*size_t tattoo_state = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PARASITES:
{
/* BOGUS: we may need these for IPTC stuff */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
/*
gssize_t base = info->cp;
GimpParasite *p;
while (info->cp - base < prop_size)
{
p = xcf_load_parasite (info);
gimp_image_parasite_attach (gimage, p);
gimp_parasite_free (p);
}
if (info->cp - base != prop_size)
g_message ("Error detected while loading an image's parasites");
*/
}
break;
case PROP_UNIT:
{
/* BOGUS: ignore for now... */
/*size_t unit = */ (void) ReadBlobMSBLong(image);
}
break;
case PROP_PATHS:
{
/* BOGUS: just skip it for now */
if (DiscardBlobBytes(image,prop_size) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
/*
PathList *paths = xcf_load_bzpaths (gimage, info);
gimp_image_set_paths (gimage, paths);
*/
}
break;
case PROP_USER_UNIT:
{
char unit_string[1000];
/*BOGUS: ignored for now */
/*float factor = (float) */ (void) ReadBlobMSBLong(image);
/* size_t digits = */ (void) ReadBlobMSBLong(image);
for (i=0; i<5; i++)
(void) ReadBlobStringWithLongSize(image, unit_string,
sizeof(unit_string),exception);
}
break;
default:
{
int buf[16];
ssize_t amount;
/* read over it... */
while ((prop_size > 0) && (EOFBlob(image) == MagickFalse))
{
amount=(ssize_t) MagickMin(16, prop_size);
amount=(ssize_t) ReadBlob(image,(size_t) amount,(unsigned char *) &buf);
if (!amount)
ThrowReaderException(CorruptImageError,"CorruptImage");
prop_size -= (size_t) MagickMin(16,(size_t) amount);
}
}
break;
}
}
if (foundPropEnd == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
{
; /* do nothing, were just pinging! */
}
else
{
int
current_layer = 0,
foundAllLayers = MagickFalse,
number_layers = 0;
MagickOffsetType
oldPos=TellBlob(image);
XCFLayerInfo
*layer_info;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
the read pointer
*/
do
{
ssize_t offset = (int) ReadBlobMSBLong(image);
if (offset == 0)
foundAllLayers=MagickTrue;
else
number_layers++;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
} while (foundAllLayers == MagickFalse);
doc_info.number_layers=number_layers;
offset=SeekBlob(image,oldPos,SEEK_SET); /* restore the position! */
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* allocate our array of layer info blocks */
length=(size_t) number_layers;
layer_info=(XCFLayerInfo *) AcquireQuantumMemory(length,
sizeof(*layer_info));
if (layer_info == (XCFLayerInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(layer_info,0,number_layers*sizeof(XCFLayerInfo));
for ( ; ; )
{
MagickBooleanType
layer_ok;
MagickOffsetType
offset,
saved_pos;
/* read in the offset of the next layer */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
/* if the offset is 0 then we are at the end
* of the layer list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next layer offset is stored.
*/
saved_pos=TellBlob(image);
/* seek to the layer offset */
offset=SeekBlob(image,offset,SEEK_SET);
/* read in the layer */
layer_ok=ReadOneLayer(image_info,image,&doc_info,
&layer_info[current_layer],current_layer,exception);
if (layer_ok == MagickFalse)
{
int j;
for (j=0; j < current_layer; j++)
layer_info[j].image=DestroyImage(layer_info[j].image);
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
current_layer++;
}
#if 0
{
/* NOTE: XCF layers are REVERSED from composite order! */
signed int j;
for (j=number_layers-1; j>=0; j--) {
/* BOGUS: need to consider layer blending modes!! */
if ( layer_info[j].visible ) { /* only visible ones, please! */
CompositeImage(image, OverCompositeOp, layer_info[j].image,
layer_info[j].offset_x, layer_info[j].offset_y );
layer_info[j].image =DestroyImage( layer_info[j].image );
/* If we do this, we'll get REAL gray images! */
if ( image_type == GIMP_GRAY ) {
QuantizeInfo qi;
GetQuantizeInfo(&qi);
qi.colorspace = GRAYColorspace;
QuantizeImage( &qi, layer_info[j].image );
}
}
}
}
#else
{
/* NOTE: XCF layers are REVERSED from composite order! */
ssize_t j;
/* now reverse the order of the layers as they are put
into subimages
*/
for (j=(ssize_t) number_layers-1; j >= 0; j--)
AppendImageToList(&image,layer_info[j].image);
}
#endif
layer_info=(XCFLayerInfo *) RelinquishMagickMemory(layer_info);
#if 0 /* BOGUS: do we need the channels?? */
while (MagickTrue)
{
/* read in the offset of the next channel */
info->cp += xcf_read_int32 (info->fp, &offset, 1);
/* if the offset is 0 then we are at the end
* of the channel list.
*/
if (offset == 0)
break;
/* save the current position as it is where the
* next channel offset is stored.
*/
saved_pos = info->cp;
/* seek to the channel offset */
xcf_seek_pos (info, offset);
/* read in the layer */
channel = xcf_load_channel (info, gimage);
if (channel == 0)
goto error;
num_successful_elements++;
/* add the channel to the image if its not the selection */
if (channel != gimage->selection_mask)
gimp_image_add_channel (gimage, channel, -1);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
xcf_seek_pos (info, saved_pos);
}
#endif
}
(void) CloseBlob(image);
DestroyImage(RemoveFirstImageFromList(&image));
if (image_type == GIMP_GRAY)
image->type=GrayscaleType;
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterXCFImage() adds attributes for the XCF 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 RegisterXCFImage method is:
%
% size_t RegisterXCFImage(void)
%
*/
ModuleExport size_t RegisterXCFImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("XCF","XCF","GIMP image");
entry->decoder=(DecodeImageHandler *) ReadXCFImage;
entry->magick=(IsImageFormatHandler *) IsXCF;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r X C F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterXCFImage() removes format registrations made by the
% XCF module from the list of supported formats.
%
% The format of the UnregisterXCFImage method is:
%
% UnregisterXCFImage(void)
%
*/
ModuleExport void UnregisterXCFImage(void)
{
(void) UnregisterMagickInfo("XCF");
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5308_0 |
crossvul-cpp_data_bad_2712_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.
*
* OSPF support contributed by Jeffrey Honig (jch@mitchell.cit.cornell.edu)
*/
/* \summary: IPv6 Open Shortest Path First (OSPFv3) 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 "ospf.h"
#define OSPF_TYPE_HELLO 1 /* Hello */
#define OSPF_TYPE_DD 2 /* Database Description */
#define OSPF_TYPE_LS_REQ 3 /* Link State Request */
#define OSPF_TYPE_LS_UPDATE 4 /* Link State Update */
#define OSPF_TYPE_LS_ACK 5 /* Link State Ack */
/* Options *_options */
#define OSPF6_OPTION_V6 0x01 /* V6 bit: A bit for peeping tom */
#define OSPF6_OPTION_E 0x02 /* E bit: External routes advertised */
#define OSPF6_OPTION_MC 0x04 /* MC bit: Multicast capable */
#define OSPF6_OPTION_N 0x08 /* N bit: For type-7 LSA */
#define OSPF6_OPTION_R 0x10 /* R bit: Router bit */
#define OSPF6_OPTION_DC 0x20 /* DC bit: Demand circuits */
/* The field is actually 24-bit (RFC5340 Section A.2). */
#define OSPF6_OPTION_AF 0x0100 /* AF bit: Multiple address families */
#define OSPF6_OPTION_L 0x0200 /* L bit: Link-local signaling (LLS) */
#define OSPF6_OPTION_AT 0x0400 /* AT bit: Authentication trailer */
/* db_flags */
#define OSPF6_DB_INIT 0x04 /* */
#define OSPF6_DB_MORE 0x02
#define OSPF6_DB_MASTER 0x01
#define OSPF6_DB_M6 0x10 /* IPv6 MTU */
/* ls_type */
#define LS_TYPE_ROUTER 1 /* router link */
#define LS_TYPE_NETWORK 2 /* network link */
#define LS_TYPE_INTER_AP 3 /* Inter-Area-Prefix */
#define LS_TYPE_INTER_AR 4 /* Inter-Area-Router */
#define LS_TYPE_ASE 5 /* ASE */
#define LS_TYPE_GROUP 6 /* Group membership */
#define LS_TYPE_NSSA 7 /* NSSA */
#define LS_TYPE_LINK 8 /* Link LSA */
#define LS_TYPE_INTRA_AP 9 /* Intra-Area-Prefix */
#define LS_TYPE_INTRA_ATE 10 /* Intra-Area-TE */
#define LS_TYPE_GRACE 11 /* Grace LSA */
#define LS_TYPE_RI 12 /* Router information */
#define LS_TYPE_INTER_ASTE 13 /* Inter-AS-TE */
#define LS_TYPE_L1VPN 14 /* L1VPN */
#define LS_TYPE_MASK 0x1fff
#define LS_SCOPE_LINKLOCAL 0x0000
#define LS_SCOPE_AREA 0x2000
#define LS_SCOPE_AS 0x4000
#define LS_SCOPE_MASK 0x6000
#define LS_SCOPE_U 0x8000
/* rla_link.link_type */
#define RLA_TYPE_ROUTER 1 /* point-to-point to another router */
#define RLA_TYPE_TRANSIT 2 /* connection to transit network */
#define RLA_TYPE_VIRTUAL 4 /* virtual link */
/* rla_flags */
#define RLA_FLAG_B 0x01
#define RLA_FLAG_E 0x02
#define RLA_FLAG_V 0x04
#define RLA_FLAG_W 0x08
#define RLA_FLAG_N 0x10
/* lsa_prefix options */
#define LSA_PREFIX_OPT_NU 0x01
#define LSA_PREFIX_OPT_LA 0x02
#define LSA_PREFIX_OPT_MC 0x04
#define LSA_PREFIX_OPT_P 0x08
#define LSA_PREFIX_OPT_DN 0x10
/* sla_tosmetric breakdown */
#define SLA_MASK_TOS 0x7f000000
#define SLA_MASK_METRIC 0x00ffffff
#define SLA_SHIFT_TOS 24
/* asla_metric */
#define ASLA_FLAG_FWDADDR 0x02000000
#define ASLA_FLAG_ROUTETAG 0x01000000
#define ASLA_MASK_METRIC 0x00ffffff
/* RFC6506 Section 4.1 */
#define OSPF6_AT_HDRLEN 16U
#define OSPF6_AUTH_TYPE_HMAC 0x0001
typedef uint32_t rtrid_t;
/* link state advertisement header */
struct lsa6_hdr {
uint16_t ls_age;
uint16_t ls_type;
rtrid_t ls_stateid;
rtrid_t ls_router;
uint32_t ls_seq;
uint16_t ls_chksum;
uint16_t ls_length;
};
/* Length of an IPv6 address, in bytes. */
#define IPV6_ADDR_LEN_BYTES (128/8)
struct lsa6_prefix {
uint8_t lsa_p_len;
uint8_t lsa_p_opt;
uint16_t lsa_p_metric;
uint8_t lsa_p_prefix[IPV6_ADDR_LEN_BYTES]; /* maximum length */
};
/* link state advertisement */
struct lsa6 {
struct lsa6_hdr ls_hdr;
/* Link state types */
union {
/* Router links advertisements */
struct {
union {
uint8_t flg;
uint32_t opt;
} rla_flgandopt;
#define rla_flags rla_flgandopt.flg
#define rla_options rla_flgandopt.opt
struct rlalink6 {
uint8_t link_type;
uint8_t link_zero[1];
uint16_t link_metric;
uint32_t link_ifid;
uint32_t link_nifid;
rtrid_t link_nrtid;
} rla_link[1]; /* may repeat */
} un_rla;
/* Network links advertisements */
struct {
uint32_t nla_options;
rtrid_t nla_router[1]; /* may repeat */
} un_nla;
/* Inter Area Prefix LSA */
struct {
uint32_t inter_ap_metric;
struct lsa6_prefix inter_ap_prefix[1];
} un_inter_ap;
/* AS external links advertisements */
struct {
uint32_t asla_metric;
struct lsa6_prefix asla_prefix[1];
/* some optional fields follow */
} un_asla;
#if 0
/* Summary links advertisements */
struct {
struct in_addr sla_mask;
uint32_t sla_tosmetric[1]; /* may repeat */
} un_sla;
/* Multicast group membership */
struct mcla {
uint32_t mcla_vtype;
struct in_addr mcla_vid;
} un_mcla[1];
#endif
/* Type 7 LSA */
/* Link LSA */
struct llsa {
union {
uint8_t pri;
uint32_t opt;
} llsa_priandopt;
#define llsa_priority llsa_priandopt.pri
#define llsa_options llsa_priandopt.opt
struct in6_addr llsa_lladdr;
uint32_t llsa_nprefix;
struct lsa6_prefix llsa_prefix[1];
} un_llsa;
/* Intra-Area-Prefix */
struct {
uint16_t intra_ap_nprefix;
uint16_t intra_ap_lstype;
rtrid_t intra_ap_lsid;
rtrid_t intra_ap_rtid;
struct lsa6_prefix intra_ap_prefix[1];
} un_intra_ap;
} lsa_un;
};
/*
* the main header
*/
struct ospf6hdr {
uint8_t ospf6_version;
uint8_t ospf6_type;
uint16_t ospf6_len;
rtrid_t ospf6_routerid;
rtrid_t ospf6_areaid;
uint16_t ospf6_chksum;
uint8_t ospf6_instanceid;
uint8_t ospf6_rsvd;
};
/*
* The OSPF6 header length is 16 bytes, regardless of how your compiler
* might choose to pad the above structure.
*/
#define OSPF6HDR_LEN 16
/* Hello packet */
struct hello6 {
uint32_t hello_ifid;
union {
uint8_t pri;
uint32_t opt;
} hello_priandopt;
#define hello_priority hello_priandopt.pri
#define hello_options hello_priandopt.opt
uint16_t hello_helloint;
uint16_t hello_deadint;
rtrid_t hello_dr;
rtrid_t hello_bdr;
rtrid_t hello_neighbor[1]; /* may repeat */
};
/* Database Description packet */
struct dd6 {
uint32_t db_options;
uint16_t db_mtu;
uint8_t db_mbz;
uint8_t db_flags;
uint32_t db_seq;
struct lsa6_hdr db_lshdr[1]; /* may repeat */
};
/* Link State Request */
struct lsr6 {
uint16_t ls_mbz;
uint16_t ls_type;
rtrid_t ls_stateid;
rtrid_t ls_router;
};
/* Link State Update */
struct lsu6 {
uint32_t lsu_count;
struct lsa6 lsu_lsa[1]; /* may repeat */
};
static const char tstr[] = " [|ospf3]";
static const struct tok ospf6_option_values[] = {
{ OSPF6_OPTION_V6, "V6" },
{ OSPF6_OPTION_E, "External" },
{ OSPF6_OPTION_MC, "Deprecated" },
{ OSPF6_OPTION_N, "NSSA" },
{ OSPF6_OPTION_R, "Router" },
{ OSPF6_OPTION_DC, "Demand Circuit" },
{ OSPF6_OPTION_AF, "AFs Support" },
{ OSPF6_OPTION_L, "LLS" },
{ OSPF6_OPTION_AT, "Authentication Trailer" },
{ 0, NULL }
};
static const struct tok ospf6_rla_flag_values[] = {
{ RLA_FLAG_B, "ABR" },
{ RLA_FLAG_E, "External" },
{ RLA_FLAG_V, "Virtual-Link Endpoint" },
{ RLA_FLAG_W, "Wildcard Receiver" },
{ RLA_FLAG_N, "NSSA Translator" },
{ 0, NULL }
};
static const struct tok ospf6_asla_flag_values[] = {
{ ASLA_FLAG_EXTERNAL, "External Type 2" },
{ ASLA_FLAG_FWDADDR, "Forwarding" },
{ ASLA_FLAG_ROUTETAG, "Tag" },
{ 0, NULL }
};
static const struct tok ospf6_type_values[] = {
{ OSPF_TYPE_HELLO, "Hello" },
{ OSPF_TYPE_DD, "Database Description" },
{ OSPF_TYPE_LS_REQ, "LS-Request" },
{ OSPF_TYPE_LS_UPDATE, "LS-Update" },
{ OSPF_TYPE_LS_ACK, "LS-Ack" },
{ 0, NULL }
};
static const struct tok ospf6_lsa_values[] = {
{ LS_TYPE_ROUTER, "Router" },
{ LS_TYPE_NETWORK, "Network" },
{ LS_TYPE_INTER_AP, "Inter-Area Prefix" },
{ LS_TYPE_INTER_AR, "Inter-Area Router" },
{ LS_TYPE_ASE, "External" },
{ LS_TYPE_GROUP, "Deprecated" },
{ LS_TYPE_NSSA, "NSSA" },
{ LS_TYPE_LINK, "Link" },
{ LS_TYPE_INTRA_AP, "Intra-Area Prefix" },
{ LS_TYPE_INTRA_ATE, "Intra-Area TE" },
{ LS_TYPE_GRACE, "Grace" },
{ LS_TYPE_RI, "Router Information" },
{ LS_TYPE_INTER_ASTE, "Inter-AS-TE" },
{ LS_TYPE_L1VPN, "Layer 1 VPN" },
{ 0, NULL }
};
static const struct tok ospf6_ls_scope_values[] = {
{ LS_SCOPE_LINKLOCAL, "Link Local" },
{ LS_SCOPE_AREA, "Area Local" },
{ LS_SCOPE_AS, "Domain Wide" },
{ 0, NULL }
};
static const struct tok ospf6_dd_flag_values[] = {
{ OSPF6_DB_INIT, "Init" },
{ OSPF6_DB_MORE, "More" },
{ OSPF6_DB_MASTER, "Master" },
{ OSPF6_DB_M6, "IPv6 MTU" },
{ 0, NULL }
};
static const struct tok ospf6_lsa_prefix_option_values[] = {
{ LSA_PREFIX_OPT_NU, "No Unicast" },
{ LSA_PREFIX_OPT_LA, "Local address" },
{ LSA_PREFIX_OPT_MC, "Deprecated" },
{ LSA_PREFIX_OPT_P, "Propagate" },
{ LSA_PREFIX_OPT_DN, "Down" },
{ 0, NULL }
};
static const struct tok ospf6_auth_type_str[] = {
{ OSPF6_AUTH_TYPE_HMAC, "HMAC" },
{ 0, NULL }
};
static void
ospf6_print_ls_type(netdissect_options *ndo,
register u_int ls_type, register const rtrid_t *ls_stateid)
{
ND_PRINT((ndo, "\n\t %s LSA (%d), %s Scope%s, LSA-ID %s",
tok2str(ospf6_lsa_values, "Unknown", ls_type & LS_TYPE_MASK),
ls_type & LS_TYPE_MASK,
tok2str(ospf6_ls_scope_values, "Unknown", ls_type & LS_SCOPE_MASK),
ls_type &0x8000 ? ", transitive" : "", /* U-bit */
ipaddr_string(ndo, ls_stateid)));
}
static int
ospf6_print_lshdr(netdissect_options *ndo,
register const struct lsa6_hdr *lshp, const u_char *dataend)
{
if ((const u_char *)(lshp + 1) > dataend)
goto trunc;
ND_TCHECK(lshp->ls_type);
ND_TCHECK(lshp->ls_seq);
ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u",
ipaddr_string(ndo, &lshp->ls_router),
EXTRACT_32BITS(&lshp->ls_seq),
EXTRACT_16BITS(&lshp->ls_age),
EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr)));
ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid);
return (0);
trunc:
return (1);
}
static int
ospf6_print_lsaprefix(netdissect_options *ndo,
const uint8_t *tptr, u_int lsa_length)
{
const struct lsa6_prefix *lsapp = (const struct lsa6_prefix *)tptr;
u_int wordlen;
struct in6_addr prefix;
if (lsa_length < sizeof (*lsapp) - IPV6_ADDR_LEN_BYTES)
goto trunc;
lsa_length -= sizeof (*lsapp) - IPV6_ADDR_LEN_BYTES;
ND_TCHECK2(*lsapp, sizeof (*lsapp) - IPV6_ADDR_LEN_BYTES);
wordlen = (lsapp->lsa_p_len + 31) / 32;
if (wordlen * 4 > sizeof(struct in6_addr)) {
ND_PRINT((ndo, " bogus prefixlen /%d", lsapp->lsa_p_len));
goto trunc;
}
if (lsa_length < wordlen * 4)
goto trunc;
lsa_length -= wordlen * 4;
ND_TCHECK2(lsapp->lsa_p_prefix, wordlen * 4);
memset(&prefix, 0, sizeof(prefix));
memcpy(&prefix, lsapp->lsa_p_prefix, wordlen * 4);
ND_PRINT((ndo, "\n\t\t%s/%d", ip6addr_string(ndo, &prefix),
lsapp->lsa_p_len));
if (lsapp->lsa_p_opt) {
ND_PRINT((ndo, ", Options [%s]",
bittok2str(ospf6_lsa_prefix_option_values,
"none", lsapp->lsa_p_opt)));
}
ND_PRINT((ndo, ", metric %u", EXTRACT_16BITS(&lsapp->lsa_p_metric)));
return sizeof(*lsapp) - IPV6_ADDR_LEN_BYTES + wordlen * 4;
trunc:
return -1;
}
/*
* Print a single link state advertisement. If truncated return 1, else 0.
*/
static int
ospf6_print_lsa(netdissect_options *ndo,
register const struct lsa6 *lsap, const u_char *dataend)
{
register const struct rlalink6 *rlp;
#if 0
register const struct tos_metric *tosp;
#endif
register const rtrid_t *ap;
#if 0
register const struct aslametric *almp;
register const struct mcla *mcp;
#endif
register const struct llsa *llsap;
register const struct lsa6_prefix *lsapp;
#if 0
register const uint32_t *lp;
#endif
register u_int prefixes;
register int bytelen;
register u_int length, lsa_length;
uint32_t flags32;
const uint8_t *tptr;
if (ospf6_print_lshdr(ndo, &lsap->ls_hdr, dataend))
return (1);
ND_TCHECK(lsap->ls_hdr.ls_length);
length = EXTRACT_16BITS(&lsap->ls_hdr.ls_length);
/*
* The LSA length includes the length of the header;
* it must have a value that's at least that length.
* If it does, find the length of what follows the
* header.
*/
if (length < sizeof(struct lsa6_hdr) || (const u_char *)lsap + length > dataend)
return (1);
lsa_length = length - sizeof(struct lsa6_hdr);
tptr = (const uint8_t *)lsap+sizeof(struct lsa6_hdr);
switch (EXTRACT_16BITS(&lsap->ls_hdr.ls_type)) {
case LS_TYPE_ROUTER | LS_SCOPE_AREA:
if (lsa_length < sizeof (lsap->lsa_un.un_rla.rla_options))
return (1);
lsa_length -= sizeof (lsap->lsa_un.un_rla.rla_options);
ND_TCHECK(lsap->lsa_un.un_rla.rla_options);
ND_PRINT((ndo, "\n\t Options [%s]",
bittok2str(ospf6_option_values, "none",
EXTRACT_32BITS(&lsap->lsa_un.un_rla.rla_options))));
ND_PRINT((ndo, ", RLA-Flags [%s]",
bittok2str(ospf6_rla_flag_values, "none",
lsap->lsa_un.un_rla.rla_flags)));
rlp = lsap->lsa_un.un_rla.rla_link;
while (lsa_length != 0) {
if (lsa_length < sizeof (*rlp))
return (1);
lsa_length -= sizeof (*rlp);
ND_TCHECK(*rlp);
switch (rlp->link_type) {
case RLA_TYPE_VIRTUAL:
ND_PRINT((ndo, "\n\t Virtual Link: Neighbor Router-ID %s"
"\n\t Neighbor Interface-ID %s, Interface %s",
ipaddr_string(ndo, &rlp->link_nrtid),
ipaddr_string(ndo, &rlp->link_nifid),
ipaddr_string(ndo, &rlp->link_ifid)));
break;
case RLA_TYPE_ROUTER:
ND_PRINT((ndo, "\n\t Neighbor Router-ID %s"
"\n\t Neighbor Interface-ID %s, Interface %s",
ipaddr_string(ndo, &rlp->link_nrtid),
ipaddr_string(ndo, &rlp->link_nifid),
ipaddr_string(ndo, &rlp->link_ifid)));
break;
case RLA_TYPE_TRANSIT:
ND_PRINT((ndo, "\n\t Neighbor Network-ID %s"
"\n\t Neighbor Interface-ID %s, Interface %s",
ipaddr_string(ndo, &rlp->link_nrtid),
ipaddr_string(ndo, &rlp->link_nifid),
ipaddr_string(ndo, &rlp->link_ifid)));
break;
default:
ND_PRINT((ndo, "\n\t Unknown Router Links Type 0x%02x",
rlp->link_type));
return (0);
}
ND_PRINT((ndo, ", metric %d", EXTRACT_16BITS(&rlp->link_metric)));
rlp++;
}
break;
case LS_TYPE_NETWORK | LS_SCOPE_AREA:
if (lsa_length < sizeof (lsap->lsa_un.un_nla.nla_options))
return (1);
lsa_length -= sizeof (lsap->lsa_un.un_nla.nla_options);
ND_TCHECK(lsap->lsa_un.un_nla.nla_options);
ND_PRINT((ndo, "\n\t Options [%s]",
bittok2str(ospf6_option_values, "none",
EXTRACT_32BITS(&lsap->lsa_un.un_nla.nla_options))));
ND_PRINT((ndo, "\n\t Connected Routers:"));
ap = lsap->lsa_un.un_nla.nla_router;
while (lsa_length != 0) {
if (lsa_length < sizeof (*ap))
return (1);
lsa_length -= sizeof (*ap);
ND_TCHECK(*ap);
ND_PRINT((ndo, "\n\t\t%s", ipaddr_string(ndo, ap)));
++ap;
}
break;
case LS_TYPE_INTER_AP | LS_SCOPE_AREA:
if (lsa_length < sizeof (lsap->lsa_un.un_inter_ap.inter_ap_metric))
return (1);
lsa_length -= sizeof (lsap->lsa_un.un_inter_ap.inter_ap_metric);
ND_TCHECK(lsap->lsa_un.un_inter_ap.inter_ap_metric);
ND_PRINT((ndo, ", metric %u",
EXTRACT_32BITS(&lsap->lsa_un.un_inter_ap.inter_ap_metric) & SLA_MASK_METRIC));
tptr = (const uint8_t *)lsap->lsa_un.un_inter_ap.inter_ap_prefix;
while (lsa_length != 0) {
bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length);
if (bytelen < 0)
goto trunc;
lsa_length -= bytelen;
tptr += bytelen;
}
break;
case LS_TYPE_ASE | LS_SCOPE_AS:
if (lsa_length < sizeof (lsap->lsa_un.un_asla.asla_metric))
return (1);
lsa_length -= sizeof (lsap->lsa_un.un_asla.asla_metric);
ND_TCHECK(lsap->lsa_un.un_asla.asla_metric);
flags32 = EXTRACT_32BITS(&lsap->lsa_un.un_asla.asla_metric);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(ospf6_asla_flag_values, "none", flags32)));
ND_PRINT((ndo, " metric %u",
EXTRACT_32BITS(&lsap->lsa_un.un_asla.asla_metric) &
ASLA_MASK_METRIC));
tptr = (const uint8_t *)lsap->lsa_un.un_asla.asla_prefix;
lsapp = (const struct lsa6_prefix *)tptr;
bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length);
if (bytelen < 0)
goto trunc;
lsa_length -= bytelen;
tptr += bytelen;
if ((flags32 & ASLA_FLAG_FWDADDR) != 0) {
const struct in6_addr *fwdaddr6;
fwdaddr6 = (const struct in6_addr *)tptr;
if (lsa_length < sizeof (*fwdaddr6))
return (1);
lsa_length -= sizeof (*fwdaddr6);
ND_TCHECK(*fwdaddr6);
ND_PRINT((ndo, " forward %s",
ip6addr_string(ndo, fwdaddr6)));
tptr += sizeof(*fwdaddr6);
}
if ((flags32 & ASLA_FLAG_ROUTETAG) != 0) {
if (lsa_length < sizeof (uint32_t))
return (1);
lsa_length -= sizeof (uint32_t);
ND_TCHECK(*(const uint32_t *)tptr);
ND_PRINT((ndo, " tag %s",
ipaddr_string(ndo, (const uint32_t *)tptr)));
tptr += sizeof(uint32_t);
}
if (lsapp->lsa_p_metric) {
if (lsa_length < sizeof (uint32_t))
return (1);
lsa_length -= sizeof (uint32_t);
ND_TCHECK(*(const uint32_t *)tptr);
ND_PRINT((ndo, " RefLSID: %s",
ipaddr_string(ndo, (const uint32_t *)tptr)));
tptr += sizeof(uint32_t);
}
break;
case LS_TYPE_LINK:
/* Link LSA */
llsap = &lsap->lsa_un.un_llsa;
if (lsa_length < sizeof (llsap->llsa_priandopt))
return (1);
lsa_length -= sizeof (llsap->llsa_priandopt);
ND_TCHECK(llsap->llsa_priandopt);
ND_PRINT((ndo, "\n\t Options [%s]",
bittok2str(ospf6_option_values, "none",
EXTRACT_32BITS(&llsap->llsa_options))));
if (lsa_length < sizeof (llsap->llsa_lladdr) + sizeof (llsap->llsa_nprefix))
return (1);
lsa_length -= sizeof (llsap->llsa_lladdr) + sizeof (llsap->llsa_nprefix);
prefixes = EXTRACT_32BITS(&llsap->llsa_nprefix);
ND_PRINT((ndo, "\n\t Priority %d, Link-local address %s, Prefixes %d:",
llsap->llsa_priority,
ip6addr_string(ndo, &llsap->llsa_lladdr),
prefixes));
tptr = (const uint8_t *)llsap->llsa_prefix;
while (prefixes > 0) {
bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length);
if (bytelen < 0)
goto trunc;
prefixes--;
lsa_length -= bytelen;
tptr += bytelen;
}
break;
case LS_TYPE_INTRA_AP | LS_SCOPE_AREA:
/* Intra-Area-Prefix LSA */
if (lsa_length < sizeof (lsap->lsa_un.un_intra_ap.intra_ap_rtid))
return (1);
lsa_length -= sizeof (lsap->lsa_un.un_intra_ap.intra_ap_rtid);
ND_TCHECK(lsap->lsa_un.un_intra_ap.intra_ap_rtid);
ospf6_print_ls_type(ndo,
EXTRACT_16BITS(&lsap->lsa_un.un_intra_ap.intra_ap_lstype),
&lsap->lsa_un.un_intra_ap.intra_ap_lsid);
if (lsa_length < sizeof (lsap->lsa_un.un_intra_ap.intra_ap_nprefix))
return (1);
lsa_length -= sizeof (lsap->lsa_un.un_intra_ap.intra_ap_nprefix);
ND_TCHECK(lsap->lsa_un.un_intra_ap.intra_ap_nprefix);
prefixes = EXTRACT_16BITS(&lsap->lsa_un.un_intra_ap.intra_ap_nprefix);
ND_PRINT((ndo, "\n\t Prefixes %d:", prefixes));
tptr = (const uint8_t *)lsap->lsa_un.un_intra_ap.intra_ap_prefix;
while (prefixes > 0) {
bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length);
if (bytelen < 0)
goto trunc;
prefixes--;
lsa_length -= bytelen;
tptr += bytelen;
}
break;
case LS_TYPE_GRACE | LS_SCOPE_LINKLOCAL:
if (ospf_print_grace_lsa(ndo, tptr, lsa_length) == -1) {
return 1;
}
break;
case LS_TYPE_INTRA_ATE | LS_SCOPE_LINKLOCAL:
if (ospf_print_te_lsa(ndo, tptr, lsa_length) == -1) {
return 1;
}
break;
default:
if(!print_unknown_data(ndo,tptr,
"\n\t ",
lsa_length)) {
return (1);
}
break;
}
return (0);
trunc:
return (1);
}
static int
ospf6_decode_v3(netdissect_options *ndo,
register const struct ospf6hdr *op,
register const u_char *dataend)
{
register const rtrid_t *ap;
register const struct lsr6 *lsrp;
register const struct lsa6_hdr *lshp;
register const struct lsa6 *lsap;
register int i;
switch (op->ospf6_type) {
case OSPF_TYPE_HELLO: {
register const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN);
ND_PRINT((ndo, "\n\tOptions [%s]",
bittok2str(ospf6_option_values, "none",
EXTRACT_32BITS(&hellop->hello_options))));
ND_TCHECK(hellop->hello_deadint);
ND_PRINT((ndo, "\n\t Hello Timer %us, Dead Timer %us, Interface-ID %s, Priority %u",
EXTRACT_16BITS(&hellop->hello_helloint),
EXTRACT_16BITS(&hellop->hello_deadint),
ipaddr_string(ndo, &hellop->hello_ifid),
hellop->hello_priority));
ND_TCHECK(hellop->hello_dr);
if (EXTRACT_32BITS(&hellop->hello_dr) != 0)
ND_PRINT((ndo, "\n\t Designated Router %s",
ipaddr_string(ndo, &hellop->hello_dr)));
ND_TCHECK(hellop->hello_bdr);
if (EXTRACT_32BITS(&hellop->hello_bdr) != 0)
ND_PRINT((ndo, ", Backup Designated Router %s",
ipaddr_string(ndo, &hellop->hello_bdr)));
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, "\n\t Neighbor List:"));
ap = hellop->hello_neighbor;
while ((const u_char *)ap < dataend) {
ND_TCHECK(*ap);
ND_PRINT((ndo, "\n\t %s", ipaddr_string(ndo, ap)));
++ap;
}
}
break; /* HELLO */
}
case OSPF_TYPE_DD: {
register const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN);
ND_TCHECK(ddp->db_options);
ND_PRINT((ndo, "\n\tOptions [%s]",
bittok2str(ospf6_option_values, "none",
EXTRACT_32BITS(&ddp->db_options))));
ND_TCHECK(ddp->db_flags);
ND_PRINT((ndo, ", DD Flags [%s]",
bittok2str(ospf6_dd_flag_values,"none",ddp->db_flags)));
ND_TCHECK(ddp->db_seq);
ND_PRINT((ndo, ", MTU %u, DD-Sequence 0x%08x",
EXTRACT_16BITS(&ddp->db_mtu),
EXTRACT_32BITS(&ddp->db_seq)));
if (ndo->ndo_vflag > 1) {
/* Print all the LS adv's */
lshp = ddp->db_lshdr;
while ((const u_char *)lshp < dataend) {
if (ospf6_print_lshdr(ndo, lshp++, dataend))
goto trunc;
}
}
break;
}
case OSPF_TYPE_LS_REQ:
if (ndo->ndo_vflag > 1) {
lsrp = (const struct lsr6 *)((const uint8_t *)op + OSPF6HDR_LEN);
while ((const u_char *)lsrp < dataend) {
ND_TCHECK(*lsrp);
ND_PRINT((ndo, "\n\t Advertising Router %s",
ipaddr_string(ndo, &lsrp->ls_router)));
ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsrp->ls_type),
&lsrp->ls_stateid);
++lsrp;
}
}
break;
case OSPF_TYPE_LS_UPDATE:
if (ndo->ndo_vflag > 1) {
register const struct lsu6 *lsup = (const struct lsu6 *)((const uint8_t *)op + OSPF6HDR_LEN);
ND_TCHECK(lsup->lsu_count);
i = EXTRACT_32BITS(&lsup->lsu_count);
lsap = lsup->lsu_lsa;
while ((const u_char *)lsap < dataend && i--) {
if (ospf6_print_lsa(ndo, lsap, dataend))
goto trunc;
lsap = (const struct lsa6 *)((const u_char *)lsap +
EXTRACT_16BITS(&lsap->ls_hdr.ls_length));
}
}
break;
case OSPF_TYPE_LS_ACK:
if (ndo->ndo_vflag > 1) {
lshp = (const struct lsa6_hdr *)((const uint8_t *)op + OSPF6HDR_LEN);
while ((const u_char *)lshp < dataend) {
if (ospf6_print_lshdr(ndo, lshp++, dataend))
goto trunc;
}
}
break;
default:
break;
}
return (0);
trunc:
return (1);
}
/* RFC5613 Section 2.2 (w/o the TLVs) */
static int
ospf6_print_lls(netdissect_options *ndo,
const u_char *cp, const u_int len)
{
uint16_t llsdatalen;
if (len == 0)
return 0;
if (len < OSPF_LLS_HDRLEN)
goto trunc;
/* Checksum */
ND_TCHECK2(*cp, 2);
ND_PRINT((ndo, "\n\tLLS Checksum 0x%04x", EXTRACT_16BITS(cp)));
cp += 2;
/* LLS Data Length */
ND_TCHECK2(*cp, 2);
llsdatalen = EXTRACT_16BITS(cp);
ND_PRINT((ndo, ", Data Length %u", llsdatalen));
if (llsdatalen < OSPF_LLS_HDRLEN || llsdatalen > len)
goto trunc;
cp += 2;
/* LLS TLVs */
ND_TCHECK2(*cp, llsdatalen - OSPF_LLS_HDRLEN);
/* FIXME: code in print-ospf.c can be reused to decode the TLVs */
return llsdatalen;
trunc:
return -1;
}
/* RFC6506 Section 4.1 */
static int
ospf6_decode_at(netdissect_options *ndo,
const u_char *cp, const u_int len)
{
uint16_t authdatalen;
if (len == 0)
return 0;
if (len < OSPF6_AT_HDRLEN)
goto trunc;
/* Authentication Type */
ND_TCHECK2(*cp, 2);
ND_PRINT((ndo, "\n\tAuthentication Type %s", tok2str(ospf6_auth_type_str, "unknown (0x%04x)", EXTRACT_16BITS(cp))));
cp += 2;
/* Auth Data Len */
ND_TCHECK2(*cp, 2);
authdatalen = EXTRACT_16BITS(cp);
ND_PRINT((ndo, ", Length %u", authdatalen));
if (authdatalen < OSPF6_AT_HDRLEN || authdatalen > len)
goto trunc;
cp += 2;
/* Reserved */
ND_TCHECK2(*cp, 2);
cp += 2;
/* Security Association ID */
ND_TCHECK2(*cp, 2);
ND_PRINT((ndo, ", SAID %u", EXTRACT_16BITS(cp)));
cp += 2;
/* Cryptographic Sequence Number (High-Order 32 Bits) */
ND_TCHECK2(*cp, 4);
ND_PRINT((ndo, ", CSN 0x%08x", EXTRACT_32BITS(cp)));
cp += 4;
/* Cryptographic Sequence Number (Low-Order 32 Bits) */
ND_TCHECK2(*cp, 4);
ND_PRINT((ndo, ":%08x", EXTRACT_32BITS(cp)));
cp += 4;
/* Authentication Data */
ND_TCHECK2(*cp, authdatalen - OSPF6_AT_HDRLEN);
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,cp, "\n\tAuthentication Data ", authdatalen - OSPF6_AT_HDRLEN);
return 0;
trunc:
return 1;
}
/* The trailing data may include LLS and/or AT data (in this specific order).
* LLS data may be present only in Hello and DBDesc packets with the L-bit set.
* AT data may be present in Hello and DBDesc packets with the AT-bit set or in
* any other packet type, thus decode the AT data regardless of the AT-bit.
*/
static int
ospf6_decode_v3_trailer(netdissect_options *ndo,
const struct ospf6hdr *op, const u_char *cp, const unsigned len)
{
int llslen = 0;
int lls_hello = 0;
int lls_dd = 0;
if (op->ospf6_type == OSPF_TYPE_HELLO) {
const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN);
if (EXTRACT_32BITS(&hellop->hello_options) & OSPF6_OPTION_L)
lls_hello = 1;
} else if (op->ospf6_type == OSPF_TYPE_DD) {
const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN);
if (EXTRACT_32BITS(&ddp->db_options) & OSPF6_OPTION_L)
lls_dd = 1;
}
if ((lls_hello || lls_dd) && (llslen = ospf6_print_lls(ndo, cp, len)) < 0)
goto trunc;
return ospf6_decode_at(ndo, cp + llslen, len - llslen);
trunc:
return 1;
}
void
ospf6_print(netdissect_options *ndo,
register const u_char *bp, register u_int length)
{
register const struct ospf6hdr *op;
register const u_char *dataend;
register const char *cp;
uint16_t datalen;
op = (const struct ospf6hdr *)bp;
/* If the type is valid translate it, or just print the type */
/* value. If it's not valid, say so and return */
ND_TCHECK(op->ospf6_type);
cp = tok2str(ospf6_type_values, "unknown packet type (%u)", op->ospf6_type);
ND_PRINT((ndo, "OSPFv%u, %s, length %d", op->ospf6_version, cp, length));
if (*cp == 'u') {
return;
}
if(!ndo->ndo_vflag) { /* non verbose - so lets bail out here */
return;
}
/* OSPFv3 data always comes first and optional trailing data may follow. */
ND_TCHECK(op->ospf6_len);
datalen = EXTRACT_16BITS(&op->ospf6_len);
if (datalen > length) {
ND_PRINT((ndo, " [len %d]", datalen));
return;
}
dataend = bp + datalen;
ND_TCHECK(op->ospf6_routerid);
ND_PRINT((ndo, "\n\tRouter-ID %s", ipaddr_string(ndo, &op->ospf6_routerid)));
ND_TCHECK(op->ospf6_areaid);
if (EXTRACT_32BITS(&op->ospf6_areaid) != 0)
ND_PRINT((ndo, ", Area %s", ipaddr_string(ndo, &op->ospf6_areaid)));
else
ND_PRINT((ndo, ", Backbone Area"));
ND_TCHECK(op->ospf6_instanceid);
if (op->ospf6_instanceid)
ND_PRINT((ndo, ", Instance %u", op->ospf6_instanceid));
/* Do rest according to version. */
switch (op->ospf6_version) {
case 3:
/* ospf version 3 */
if (ospf6_decode_v3(ndo, op, dataend) ||
ospf6_decode_v3_trailer(ndo, op, dataend, length - datalen))
goto trunc;
break;
} /* end switch on version */
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2712_0 |
crossvul-cpp_data_good_2916_0 | /*
* Released under the GPLv2 only.
* SPDX-License-Identifier: GPL-2.0
*/
#include <linux/usb.h>
#include <linux/usb/ch9.h>
#include <linux/usb/hcd.h>
#include <linux/usb/quirks.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <asm/byteorder.h>
#include "usb.h"
#define USB_MAXALTSETTING 128 /* Hard limit */
#define USB_MAXCONFIG 8 /* Arbitrary limit */
static inline const char *plural(int n)
{
return (n == 1 ? "" : "s");
}
static int find_next_descriptor(unsigned char *buffer, int size,
int dt1, int dt2, int *num_skipped)
{
struct usb_descriptor_header *h;
int n = 0;
unsigned char *buffer0 = buffer;
/* Find the next descriptor of type dt1 or dt2 */
while (size > 0) {
h = (struct usb_descriptor_header *) buffer;
if (h->bDescriptorType == dt1 || h->bDescriptorType == dt2)
break;
buffer += h->bLength;
size -= h->bLength;
++n;
}
/* Store the number of descriptors skipped and return the
* number of bytes skipped */
if (num_skipped)
*num_skipped = n;
return buffer - buffer0;
}
static void usb_parse_ssp_isoc_endpoint_companion(struct device *ddev,
int cfgno, int inum, int asnum, struct usb_host_endpoint *ep,
unsigned char *buffer, int size)
{
struct usb_ssp_isoc_ep_comp_descriptor *desc;
/*
* The SuperSpeedPlus Isoc endpoint companion descriptor immediately
* follows the SuperSpeed Endpoint Companion descriptor
*/
desc = (struct usb_ssp_isoc_ep_comp_descriptor *) buffer;
if (desc->bDescriptorType != USB_DT_SSP_ISOC_ENDPOINT_COMP ||
size < USB_DT_SSP_ISOC_EP_COMP_SIZE) {
dev_warn(ddev, "Invalid SuperSpeedPlus isoc endpoint companion"
"for config %d interface %d altsetting %d ep %d.\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
return;
}
memcpy(&ep->ssp_isoc_ep_comp, desc, USB_DT_SSP_ISOC_EP_COMP_SIZE);
}
static void usb_parse_ss_endpoint_companion(struct device *ddev, int cfgno,
int inum, int asnum, struct usb_host_endpoint *ep,
unsigned char *buffer, int size)
{
struct usb_ss_ep_comp_descriptor *desc;
int max_tx;
/* The SuperSpeed endpoint companion descriptor is supposed to
* be the first thing immediately following the endpoint descriptor.
*/
desc = (struct usb_ss_ep_comp_descriptor *) buffer;
if (desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP ||
size < USB_DT_SS_EP_COMP_SIZE) {
dev_warn(ddev, "No SuperSpeed endpoint companion for config %d "
" interface %d altsetting %d ep %d: "
"using minimum values\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
/* Fill in some default values.
* Leave bmAttributes as zero, which will mean no streams for
* bulk, and isoc won't support multiple bursts of packets.
* With bursts of only one packet, and a Mult of 1, the max
* amount of data moved per endpoint service interval is one
* packet.
*/
ep->ss_ep_comp.bLength = USB_DT_SS_EP_COMP_SIZE;
ep->ss_ep_comp.bDescriptorType = USB_DT_SS_ENDPOINT_COMP;
if (usb_endpoint_xfer_isoc(&ep->desc) ||
usb_endpoint_xfer_int(&ep->desc))
ep->ss_ep_comp.wBytesPerInterval =
ep->desc.wMaxPacketSize;
return;
}
buffer += desc->bLength;
size -= desc->bLength;
memcpy(&ep->ss_ep_comp, desc, USB_DT_SS_EP_COMP_SIZE);
/* Check the various values */
if (usb_endpoint_xfer_control(&ep->desc) && desc->bMaxBurst != 0) {
dev_warn(ddev, "Control endpoint with bMaxBurst = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to zero\n", desc->bMaxBurst,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bMaxBurst = 0;
} else if (desc->bMaxBurst > 15) {
dev_warn(ddev, "Endpoint with bMaxBurst = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to 15\n", desc->bMaxBurst,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bMaxBurst = 15;
}
if ((usb_endpoint_xfer_control(&ep->desc) ||
usb_endpoint_xfer_int(&ep->desc)) &&
desc->bmAttributes != 0) {
dev_warn(ddev, "%s endpoint with bmAttributes = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to zero\n",
usb_endpoint_xfer_control(&ep->desc) ? "Control" : "Bulk",
desc->bmAttributes,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 0;
} else if (usb_endpoint_xfer_bulk(&ep->desc) &&
desc->bmAttributes > 16) {
dev_warn(ddev, "Bulk endpoint with more than 65536 streams in "
"config %d interface %d altsetting %d ep %d: "
"setting to max\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 16;
} else if (usb_endpoint_xfer_isoc(&ep->desc) &&
!USB_SS_SSP_ISOC_COMP(desc->bmAttributes) &&
USB_SS_MULT(desc->bmAttributes) > 3) {
dev_warn(ddev, "Isoc endpoint has Mult of %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to 3\n",
USB_SS_MULT(desc->bmAttributes),
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 2;
}
if (usb_endpoint_xfer_isoc(&ep->desc))
max_tx = (desc->bMaxBurst + 1) *
(USB_SS_MULT(desc->bmAttributes)) *
usb_endpoint_maxp(&ep->desc);
else if (usb_endpoint_xfer_int(&ep->desc))
max_tx = usb_endpoint_maxp(&ep->desc) *
(desc->bMaxBurst + 1);
else
max_tx = 999999;
if (le16_to_cpu(desc->wBytesPerInterval) > max_tx) {
dev_warn(ddev, "%s endpoint with wBytesPerInterval of %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to %d\n",
usb_endpoint_xfer_isoc(&ep->desc) ? "Isoc" : "Int",
le16_to_cpu(desc->wBytesPerInterval),
cfgno, inum, asnum, ep->desc.bEndpointAddress,
max_tx);
ep->ss_ep_comp.wBytesPerInterval = cpu_to_le16(max_tx);
}
/* Parse a possible SuperSpeedPlus isoc ep companion descriptor */
if (usb_endpoint_xfer_isoc(&ep->desc) &&
USB_SS_SSP_ISOC_COMP(desc->bmAttributes))
usb_parse_ssp_isoc_endpoint_companion(ddev, cfgno, inum, asnum,
ep, buffer, size);
}
static const unsigned short low_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 8,
[USB_ENDPOINT_XFER_ISOC] = 0,
[USB_ENDPOINT_XFER_BULK] = 0,
[USB_ENDPOINT_XFER_INT] = 8,
};
static const unsigned short full_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 64,
[USB_ENDPOINT_XFER_ISOC] = 1023,
[USB_ENDPOINT_XFER_BULK] = 64,
[USB_ENDPOINT_XFER_INT] = 64,
};
static const unsigned short high_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 64,
[USB_ENDPOINT_XFER_ISOC] = 1024,
[USB_ENDPOINT_XFER_BULK] = 512,
[USB_ENDPOINT_XFER_INT] = 1024,
};
static const unsigned short super_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 512,
[USB_ENDPOINT_XFER_ISOC] = 1024,
[USB_ENDPOINT_XFER_BULK] = 1024,
[USB_ENDPOINT_XFER_INT] = 1024,
};
static int usb_parse_endpoint(struct device *ddev, int cfgno, int inum,
int asnum, struct usb_host_interface *ifp, int num_ep,
unsigned char *buffer, int size)
{
unsigned char *buffer0 = buffer;
struct usb_endpoint_descriptor *d;
struct usb_host_endpoint *endpoint;
int n, i, j, retval;
unsigned int maxp;
const unsigned short *maxpacket_maxes;
d = (struct usb_endpoint_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
n = USB_DT_ENDPOINT_AUDIO_SIZE;
else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
n = USB_DT_ENDPOINT_SIZE;
else {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint descriptor of length %d, skipping\n",
cfgno, inum, asnum, d->bLength);
goto skip_to_next_endpoint_or_interface_descriptor;
}
i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
if (i >= 16 || i == 0) {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
/* Only store as many endpoints as we have room for */
if (ifp->desc.bNumEndpoints >= num_ep)
goto skip_to_next_endpoint_or_interface_descriptor;
/* Check for duplicate endpoint addresses */
for (i = 0; i < ifp->desc.bNumEndpoints; ++i) {
if (ifp->endpoint[i].desc.bEndpointAddress ==
d->bEndpointAddress) {
dev_warn(ddev, "config %d interface %d altsetting %d has a duplicate endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
}
endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
++ifp->desc.bNumEndpoints;
memcpy(&endpoint->desc, d, n);
INIT_LIST_HEAD(&endpoint->urb_list);
/*
* Fix up bInterval values outside the legal range.
* Use 10 or 8 ms if no proper value can be guessed.
*/
i = 0; /* i = min, j = max, n = default */
j = 255;
if (usb_endpoint_xfer_int(d)) {
i = 1;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_SUPER_PLUS:
case USB_SPEED_SUPER:
case USB_SPEED_HIGH:
/*
* Many device manufacturers are using full-speed
* bInterval values in high-speed interrupt endpoint
* descriptors. Try to fix those and fall back to an
* 8-ms default value otherwise.
*/
n = fls(d->bInterval*8);
if (n == 0)
n = 7; /* 8 ms = 2^(7-1) uframes */
j = 16;
/*
* Adjust bInterval for quirked devices.
*/
/*
* This quirk fixes bIntervals reported in ms.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval) + 3, i, j);
i = j = n;
}
/*
* This quirk fixes bIntervals reported in
* linear microframes.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval), i, j);
i = j = n;
}
break;
default: /* USB_SPEED_FULL or _LOW */
/*
* For low-speed, 10 ms is the official minimum.
* But some "overclocked" devices might want faster
* polling so we'll allow it.
*/
n = 10;
break;
}
} else if (usb_endpoint_xfer_isoc(d)) {
i = 1;
j = 16;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_HIGH:
n = 7; /* 8 ms = 2^(7-1) uframes */
break;
default: /* USB_SPEED_FULL */
n = 4; /* 8 ms = 2^(4-1) frames */
break;
}
}
if (d->bInterval < i || d->bInterval > j) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X has an invalid bInterval %d, "
"changing to %d\n",
cfgno, inum, asnum,
d->bEndpointAddress, d->bInterval, n);
endpoint->desc.bInterval = n;
}
/* Some buggy low-speed devices have Bulk endpoints, which is
* explicitly forbidden by the USB spec. In an attempt to make
* them usable, we will try treating them as Interrupt endpoints.
*/
if (to_usb_device(ddev)->speed == USB_SPEED_LOW &&
usb_endpoint_xfer_bulk(d)) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X is Bulk; changing to Interrupt\n",
cfgno, inum, asnum, d->bEndpointAddress);
endpoint->desc.bmAttributes = USB_ENDPOINT_XFER_INT;
endpoint->desc.bInterval = 1;
if (usb_endpoint_maxp(&endpoint->desc) > 8)
endpoint->desc.wMaxPacketSize = cpu_to_le16(8);
}
/* Validate the wMaxPacketSize field */
maxp = usb_endpoint_maxp(&endpoint->desc);
/* Find the highest legal maxpacket size for this endpoint */
i = 0; /* additional transactions per microframe */
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_LOW:
maxpacket_maxes = low_speed_maxpacket_maxes;
break;
case USB_SPEED_FULL:
maxpacket_maxes = full_speed_maxpacket_maxes;
break;
case USB_SPEED_HIGH:
/* Bits 12..11 are allowed only for HS periodic endpoints */
if (usb_endpoint_xfer_int(d) || usb_endpoint_xfer_isoc(d)) {
i = maxp & (BIT(12) | BIT(11));
maxp &= ~i;
}
/* fallthrough */
default:
maxpacket_maxes = high_speed_maxpacket_maxes;
break;
case USB_SPEED_SUPER:
case USB_SPEED_SUPER_PLUS:
maxpacket_maxes = super_speed_maxpacket_maxes;
break;
}
j = maxpacket_maxes[usb_endpoint_type(&endpoint->desc)];
if (maxp > j) {
dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid maxpacket %d, setting to %d\n",
cfgno, inum, asnum, d->bEndpointAddress, maxp, j);
maxp = j;
endpoint->desc.wMaxPacketSize = cpu_to_le16(i | maxp);
}
/*
* Some buggy high speed devices have bulk endpoints using
* maxpacket sizes other than 512. High speed HCDs may not
* be able to handle that particular bug, so let's warn...
*/
if (to_usb_device(ddev)->speed == USB_SPEED_HIGH
&& usb_endpoint_xfer_bulk(d)) {
if (maxp != 512)
dev_warn(ddev, "config %d interface %d altsetting %d "
"bulk endpoint 0x%X has invalid maxpacket %d\n",
cfgno, inum, asnum, d->bEndpointAddress,
maxp);
}
/* Parse a possible SuperSpeed endpoint companion descriptor */
if (to_usb_device(ddev)->speed >= USB_SPEED_SUPER)
usb_parse_ss_endpoint_companion(ddev, cfgno,
inum, asnum, endpoint, buffer, size);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the next endpoint or interface descriptor */
endpoint->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
endpoint->extralen = i;
retval = buffer - buffer0 + i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "endpoint");
return retval;
skip_to_next_endpoint_or_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
void usb_release_interface_cache(struct kref *ref)
{
struct usb_interface_cache *intfc = ref_to_usb_interface_cache(ref);
int j;
for (j = 0; j < intfc->num_altsetting; j++) {
struct usb_host_interface *alt = &intfc->altsetting[j];
kfree(alt->endpoint);
kfree(alt->string);
}
kfree(intfc);
}
static int usb_parse_interface(struct device *ddev, int cfgno,
struct usb_host_config *config, unsigned char *buffer, int size,
u8 inums[], u8 nalts[])
{
unsigned char *buffer0 = buffer;
struct usb_interface_descriptor *d;
int inum, asnum;
struct usb_interface_cache *intfc;
struct usb_host_interface *alt;
int i, n;
int len, retval;
int num_ep, num_ep_orig;
d = (struct usb_interface_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength < USB_DT_INTERFACE_SIZE)
goto skip_to_next_interface_descriptor;
/* Which interface entry is this? */
intfc = NULL;
inum = d->bInterfaceNumber;
for (i = 0; i < config->desc.bNumInterfaces; ++i) {
if (inums[i] == inum) {
intfc = config->intf_cache[i];
break;
}
}
if (!intfc || intfc->num_altsetting >= nalts[i])
goto skip_to_next_interface_descriptor;
/* Check for duplicate altsetting entries */
asnum = d->bAlternateSetting;
for ((i = 0, alt = &intfc->altsetting[0]);
i < intfc->num_altsetting;
(++i, ++alt)) {
if (alt->desc.bAlternateSetting == asnum) {
dev_warn(ddev, "Duplicate descriptor for config %d "
"interface %d altsetting %d, skipping\n",
cfgno, inum, asnum);
goto skip_to_next_interface_descriptor;
}
}
++intfc->num_altsetting;
memcpy(&alt->desc, d, USB_DT_INTERFACE_SIZE);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first endpoint or interface descriptor */
alt->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
alt->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "interface");
buffer += i;
size -= i;
/* Allocate space for the right(?) number of endpoints */
num_ep = num_ep_orig = alt->desc.bNumEndpoints;
alt->desc.bNumEndpoints = 0; /* Use as a counter */
if (num_ep > USB_MAXENDPOINTS) {
dev_warn(ddev, "too many endpoints for config %d interface %d "
"altsetting %d: %d, using maximum allowed: %d\n",
cfgno, inum, asnum, num_ep, USB_MAXENDPOINTS);
num_ep = USB_MAXENDPOINTS;
}
if (num_ep > 0) {
/* Can't allocate 0 bytes */
len = sizeof(struct usb_host_endpoint) * num_ep;
alt->endpoint = kzalloc(len, GFP_KERNEL);
if (!alt->endpoint)
return -ENOMEM;
}
/* Parse all the endpoint descriptors */
n = 0;
while (size > 0) {
if (((struct usb_descriptor_header *) buffer)->bDescriptorType
== USB_DT_INTERFACE)
break;
retval = usb_parse_endpoint(ddev, cfgno, inum, asnum, alt,
num_ep, buffer, size);
if (retval < 0)
return retval;
++n;
buffer += retval;
size -= retval;
}
if (n != num_ep_orig)
dev_warn(ddev, "config %d interface %d altsetting %d has %d "
"endpoint descriptor%s, different from the interface "
"descriptor's value: %d\n",
cfgno, inum, asnum, n, plural(n), num_ep_orig);
return buffer - buffer0;
skip_to_next_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
static int usb_parse_configuration(struct usb_device *dev, int cfgidx,
struct usb_host_config *config, unsigned char *buffer, int size)
{
struct device *ddev = &dev->dev;
unsigned char *buffer0 = buffer;
int cfgno;
int nintf, nintf_orig;
int i, j, n;
struct usb_interface_cache *intfc;
unsigned char *buffer2;
int size2;
struct usb_descriptor_header *header;
int len, retval;
u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
unsigned iad_num = 0;
memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
if (config->desc.bDescriptorType != USB_DT_CONFIG ||
config->desc.bLength < USB_DT_CONFIG_SIZE ||
config->desc.bLength > size) {
dev_err(ddev, "invalid descriptor for config index %d: "
"type = 0x%X, length = %d\n", cfgidx,
config->desc.bDescriptorType, config->desc.bLength);
return -EINVAL;
}
cfgno = config->desc.bConfigurationValue;
buffer += config->desc.bLength;
size -= config->desc.bLength;
nintf = nintf_orig = config->desc.bNumInterfaces;
if (nintf > USB_MAXINTERFACES) {
dev_warn(ddev, "config %d has too many interfaces: %d, "
"using maximum allowed: %d\n",
cfgno, nintf, USB_MAXINTERFACES);
nintf = USB_MAXINTERFACES;
}
/* Go through the descriptors, checking their length and counting the
* number of altsettings for each interface */
n = 0;
for ((buffer2 = buffer, size2 = size);
size2 > 0;
(buffer2 += header->bLength, size2 -= header->bLength)) {
if (size2 < sizeof(struct usb_descriptor_header)) {
dev_warn(ddev, "config %d descriptor has %d excess "
"byte%s, ignoring\n",
cfgno, size2, plural(size2));
break;
}
header = (struct usb_descriptor_header *) buffer2;
if ((header->bLength > size2) || (header->bLength < 2)) {
dev_warn(ddev, "config %d has an invalid descriptor "
"of length %d, skipping remainder of the config\n",
cfgno, header->bLength);
break;
}
if (header->bDescriptorType == USB_DT_INTERFACE) {
struct usb_interface_descriptor *d;
int inum;
d = (struct usb_interface_descriptor *) header;
if (d->bLength < USB_DT_INTERFACE_SIZE) {
dev_warn(ddev, "config %d has an invalid "
"interface descriptor of length %d, "
"skipping\n", cfgno, d->bLength);
continue;
}
inum = d->bInterfaceNumber;
if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&
n >= nintf_orig) {
dev_warn(ddev, "config %d has more interface "
"descriptors, than it declares in "
"bNumInterfaces, ignoring interface "
"number: %d\n", cfgno, inum);
continue;
}
if (inum >= nintf_orig)
dev_warn(ddev, "config %d has an invalid "
"interface number: %d but max is %d\n",
cfgno, inum, nintf_orig - 1);
/* Have we already encountered this interface?
* Count its altsettings */
for (i = 0; i < n; ++i) {
if (inums[i] == inum)
break;
}
if (i < n) {
if (nalts[i] < 255)
++nalts[i];
} else if (n < USB_MAXINTERFACES) {
inums[n] = inum;
nalts[n] = 1;
++n;
}
} else if (header->bDescriptorType ==
USB_DT_INTERFACE_ASSOCIATION) {
struct usb_interface_assoc_descriptor *d;
d = (struct usb_interface_assoc_descriptor *)header;
if (d->bLength < USB_DT_INTERFACE_ASSOCIATION_SIZE) {
dev_warn(ddev,
"config %d has an invalid interface association descriptor of length %d, skipping\n",
cfgno, d->bLength);
continue;
}
if (iad_num == USB_MAXIADS) {
dev_warn(ddev, "found more Interface "
"Association Descriptors "
"than allocated for in "
"configuration %d\n", cfgno);
} else {
config->intf_assoc[iad_num] = d;
iad_num++;
}
} else if (header->bDescriptorType == USB_DT_DEVICE ||
header->bDescriptorType == USB_DT_CONFIG)
dev_warn(ddev, "config %d contains an unexpected "
"descriptor of type 0x%X, skipping\n",
cfgno, header->bDescriptorType);
} /* for ((buffer2 = buffer, size2 = size); ...) */
size = buffer2 - buffer;
config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
if (n != nintf)
dev_warn(ddev, "config %d has %d interface%s, different from "
"the descriptor's value: %d\n",
cfgno, n, plural(n), nintf_orig);
else if (n == 0)
dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
config->desc.bNumInterfaces = nintf = n;
/* Check for missing interface numbers */
for (i = 0; i < nintf; ++i) {
for (j = 0; j < nintf; ++j) {
if (inums[j] == i)
break;
}
if (j >= nintf)
dev_warn(ddev, "config %d has no interface number "
"%d\n", cfgno, i);
}
/* Allocate the usb_interface_caches and altsetting arrays */
for (i = 0; i < nintf; ++i) {
j = nalts[i];
if (j > USB_MAXALTSETTING) {
dev_warn(ddev, "too many alternate settings for "
"config %d interface %d: %d, "
"using maximum allowed: %d\n",
cfgno, inums[i], j, USB_MAXALTSETTING);
nalts[i] = j = USB_MAXALTSETTING;
}
len = sizeof(*intfc) + sizeof(struct usb_host_interface) * j;
config->intf_cache[i] = intfc = kzalloc(len, GFP_KERNEL);
if (!intfc)
return -ENOMEM;
kref_init(&intfc->ref);
}
/* FIXME: parse the BOS descriptor */
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first interface descriptor */
config->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, &n);
config->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "configuration");
buffer += i;
size -= i;
/* Parse all the interface/altsetting descriptors */
while (size > 0) {
retval = usb_parse_interface(ddev, cfgno, config,
buffer, size, inums, nalts);
if (retval < 0)
return retval;
buffer += retval;
size -= retval;
}
/* Check for missing altsettings */
for (i = 0; i < nintf; ++i) {
intfc = config->intf_cache[i];
for (j = 0; j < intfc->num_altsetting; ++j) {
for (n = 0; n < intfc->num_altsetting; ++n) {
if (intfc->altsetting[n].desc.
bAlternateSetting == j)
break;
}
if (n >= intfc->num_altsetting)
dev_warn(ddev, "config %d interface %d has no "
"altsetting %d\n", cfgno, inums[i], j);
}
}
return 0;
}
/* hub-only!! ... and only exported for reset/reinit path.
* otherwise used internally on disconnect/destroy path
*/
void usb_destroy_configuration(struct usb_device *dev)
{
int c, i;
if (!dev->config)
return;
if (dev->rawdescriptors) {
for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
kfree(dev->rawdescriptors[i]);
kfree(dev->rawdescriptors);
dev->rawdescriptors = NULL;
}
for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
struct usb_host_config *cf = &dev->config[c];
kfree(cf->string);
for (i = 0; i < cf->desc.bNumInterfaces; i++) {
if (cf->intf_cache[i])
kref_put(&cf->intf_cache[i]->ref,
usb_release_interface_cache);
}
}
kfree(dev->config);
dev->config = NULL;
}
/*
* Get the USB config descriptors, cache and parse'em
*
* hub-only!! ... and only in reset path, or usb_new_device()
* (used by real hubs and virtual root hubs)
*/
int usb_get_configuration(struct usb_device *dev)
{
struct device *ddev = &dev->dev;
int ncfg = dev->descriptor.bNumConfigurations;
int result = 0;
unsigned int cfgno, length;
unsigned char *bigbuffer;
struct usb_config_descriptor *desc;
cfgno = 0;
result = -ENOMEM;
if (ncfg > USB_MAXCONFIG) {
dev_warn(ddev, "too many configurations: %d, "
"using maximum allowed: %d\n", ncfg, USB_MAXCONFIG);
dev->descriptor.bNumConfigurations = ncfg = USB_MAXCONFIG;
}
if (ncfg < 1) {
dev_err(ddev, "no configurations\n");
return -EINVAL;
}
length = ncfg * sizeof(struct usb_host_config);
dev->config = kzalloc(length, GFP_KERNEL);
if (!dev->config)
goto err2;
length = ncfg * sizeof(char *);
dev->rawdescriptors = kzalloc(length, GFP_KERNEL);
if (!dev->rawdescriptors)
goto err2;
desc = kmalloc(USB_DT_CONFIG_SIZE, GFP_KERNEL);
if (!desc)
goto err2;
result = 0;
for (; cfgno < ncfg; cfgno++) {
/* We grab just the first descriptor so we know how long
* the whole configuration is */
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
desc, USB_DT_CONFIG_SIZE);
if (result < 0) {
dev_err(ddev, "unable to read config index %d "
"descriptor/%s: %d\n", cfgno, "start", result);
if (result != -EPIPE)
goto err;
dev_err(ddev, "chopping to %d config(s)\n", cfgno);
dev->descriptor.bNumConfigurations = cfgno;
break;
} else if (result < 4) {
dev_err(ddev, "config index %d descriptor too short "
"(expected %i, got %i)\n", cfgno,
USB_DT_CONFIG_SIZE, result);
result = -EINVAL;
goto err;
}
length = max((int) le16_to_cpu(desc->wTotalLength),
USB_DT_CONFIG_SIZE);
/* Now that we know the length, get the whole thing */
bigbuffer = kmalloc(length, GFP_KERNEL);
if (!bigbuffer) {
result = -ENOMEM;
goto err;
}
if (dev->quirks & USB_QUIRK_DELAY_INIT)
msleep(200);
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
bigbuffer, length);
if (result < 0) {
dev_err(ddev, "unable to read config index %d "
"descriptor/%s\n", cfgno, "all");
kfree(bigbuffer);
goto err;
}
if (result < length) {
dev_warn(ddev, "config index %d descriptor too short "
"(expected %i, got %i)\n", cfgno, length, result);
length = result;
}
dev->rawdescriptors[cfgno] = bigbuffer;
result = usb_parse_configuration(dev, cfgno,
&dev->config[cfgno], bigbuffer, length);
if (result < 0) {
++cfgno;
goto err;
}
}
result = 0;
err:
kfree(desc);
dev->descriptor.bNumConfigurations = cfgno;
err2:
if (result == -ENOMEM)
dev_err(ddev, "out of memory\n");
return result;
}
void usb_release_bos_descriptor(struct usb_device *dev)
{
if (dev->bos) {
kfree(dev->bos->desc);
kfree(dev->bos);
dev->bos = NULL;
}
}
/* Get BOS descriptor set */
int usb_get_bos_descriptor(struct usb_device *dev)
{
struct device *ddev = &dev->dev;
struct usb_bos_descriptor *bos;
struct usb_dev_cap_header *cap;
unsigned char *buffer;
int length, total_len, num, i;
int ret;
bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);
if (!bos)
return -ENOMEM;
/* Get BOS descriptor */
ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);
if (ret < USB_DT_BOS_SIZE) {
dev_err(ddev, "unable to get BOS descriptor\n");
if (ret >= 0)
ret = -ENOMSG;
kfree(bos);
return ret;
}
length = bos->bLength;
total_len = le16_to_cpu(bos->wTotalLength);
num = bos->bNumDeviceCaps;
kfree(bos);
if (total_len < length)
return -EINVAL;
dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);
if (!dev->bos)
return -ENOMEM;
/* Now let's get the whole BOS descriptor set */
buffer = kzalloc(total_len, GFP_KERNEL);
if (!buffer) {
ret = -ENOMEM;
goto err;
}
dev->bos->desc = (struct usb_bos_descriptor *)buffer;
ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);
if (ret < total_len) {
dev_err(ddev, "unable to get BOS descriptor set\n");
if (ret >= 0)
ret = -ENOMSG;
goto err;
}
total_len -= length;
for (i = 0; i < num; i++) {
buffer += length;
cap = (struct usb_dev_cap_header *)buffer;
if (total_len < sizeof(*cap) || total_len < cap->bLength) {
dev->bos->desc->bNumDeviceCaps = i;
break;
}
length = cap->bLength;
total_len -= length;
if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {
dev_warn(ddev, "descriptor type invalid, skip\n");
continue;
}
switch (cap->bDevCapabilityType) {
case USB_CAP_TYPE_WIRELESS_USB:
/* Wireless USB cap descriptor is handled by wusb */
break;
case USB_CAP_TYPE_EXT:
dev->bos->ext_cap =
(struct usb_ext_cap_descriptor *)buffer;
break;
case USB_SS_CAP_TYPE:
dev->bos->ss_cap =
(struct usb_ss_cap_descriptor *)buffer;
break;
case USB_SSP_CAP_TYPE:
dev->bos->ssp_cap =
(struct usb_ssp_cap_descriptor *)buffer;
break;
case CONTAINER_ID_TYPE:
dev->bos->ss_id =
(struct usb_ss_container_id_descriptor *)buffer;
break;
case USB_PTM_CAP_TYPE:
dev->bos->ptm_cap =
(struct usb_ptm_cap_descriptor *)buffer;
default:
break;
}
}
return 0;
err:
usb_release_bos_descriptor(dev);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2916_0 |
crossvul-cpp_data_good_508_2 | /* $Id$ */
/*
* Copyright (c) 2001-2010 Aaron Turner <aturner at synfin dot net>
* Copyright (c) 2013-2018 Fred Klassen <tcpreplay at appneta dot com> - AppNeta
*
* The Tcpreplay Suite of tools 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 with the authors permission any later version.
*
* The Tcpreplay Suite 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 the Tcpreplay Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "defines.h"
#include "common.h"
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef DEBUG
extern int debug;
#endif
/**
* this is wrapped up in a #define safe_malloc
* This function, detects failures to malloc memory and zeros out the
* memory before returning
*/
void *
_our_safe_malloc(size_t len, const char *funcname, const int line, const char *file)
{
u_char *ptr;
if ((ptr = malloc(len)) == NULL) {
fprintf(stderr, "ERROR in %s:%s() line %d: Unable to malloc() %zu bytes/n",
file, funcname, line, len);
exit(-1);
}
/* zero memory */
memset(ptr, 0, len);
/* wrapped inside an #ifdef for better performance */
dbgx(5, "Malloc'd %zu bytes in %s:%s() line %d", len, file, funcname, line);
return (void *)ptr;
}
/**
* this is wrapped up in a #define safe_realloc
* This function, detects failures to realloc memory and zeros
* out the NEW memory if len > current len. As always, remember
* to use it as:
* ptr = safe_realloc(ptr, size)
*/
void *
_our_safe_realloc(void *ptr, size_t len, const char *funcname, const int line, const char *file)
{
if ((ptr = realloc(ptr, len)) == NULL) {
fprintf(stderr, "ERROR: in %s:%s() line %d: Unable to remalloc() buffer to %zu bytes", file, funcname, line, len);
exit(-1);
}
dbgx(5, "Remalloc'd buffer to %zu bytes in %s:%s() line %d", len, file, funcname, line);
return ptr;
}
/**
* this is wrapped up in a #define safe_strdup
* This function, detects failures to realloc memory
*/
char *
_our_safe_strdup(const char *str, const char *funcname, const int line, const char *file)
{
char *newstr;
if ((newstr = (char *)malloc(strlen(str) + 1)) == NULL) {
fprintf(stderr, "ERROR in %s:%s() line %d: Unable to strdup() %zu bytes\n", file, funcname, line, strlen(str));
exit(-1);
}
memcpy(newstr, str, strlen(str) + 1);
return newstr;
}
/**
* calls free and sets to NULL.
*/
void
_our_safe_free(void *ptr, const char *funcname, const int line, const char *file)
{
assert(funcname);
assert(line);
assert(file);
if (ptr == NULL)
return;
free(ptr);
}
/**
* get next packet in pcap file
*/
u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr,
const char *funcname, const int line, const char *file)
{
u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
if (pktdata) {
if (pkthdr->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, pkthdr->len, MAXPACKET);
exit(-1);
}
if (!pkthdr->len || pkthdr->len < pkthdr->caplen) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
file, funcname, line, pkthdr->len, pkthdr->caplen);
exit(-1);
}
}
return pktdata;
}
/**
* get next packet in pcap file (extended)
*/
int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
/**
* Print various packet statistics
*/
void
packet_stats(const tcpreplay_stats_t *stats)
{
struct timeval diff;
COUNTER diff_us;
COUNTER bytes_sec = 0;
u_int32_t bytes_sec_10ths = 0;
COUNTER mb_sec = 0;
u_int32_t mb_sec_100ths = 0;
u_int32_t mb_sec_1000ths = 0;
COUNTER pkts_sec = 0;
u_int32_t pkts_sec_100ths = 0;
timersub(&stats->end_time, &stats->start_time, &diff);
diff_us = TIMEVAL_TO_MICROSEC(&diff);
if (diff_us && stats->pkts_sent && stats->bytes_sent) {
COUNTER bytes_sec_X10;
COUNTER pkts_sec_X100;
COUNTER mb_sec_X1000;
COUNTER mb_sec_X100;
if (stats->bytes_sent > 1000 * 1000 * 1000 && diff_us > 1000 * 1000) {
bytes_sec_X10 = (stats->bytes_sent * 10 * 1000) / (diff_us / 1000);
pkts_sec_X100 = (stats->pkts_sent * 100 * 1000) / (diff_us / 1000);
} else {
bytes_sec_X10 = (stats->bytes_sent * 10 * 1000 * 1000) / diff_us;
pkts_sec_X100 = (stats->pkts_sent * 100 * 1000 * 1000) / diff_us;
}
bytes_sec = bytes_sec_X10 / 10;
bytes_sec_10ths = bytes_sec_X10 % 10;
mb_sec_X1000 = (bytes_sec * 8) / 1000;
mb_sec_X100 = mb_sec_X1000 / 10;
mb_sec = mb_sec_X1000 / 1000;
mb_sec_100ths = mb_sec_X100 % 100;
mb_sec_1000ths = mb_sec_X1000 % 1000;
pkts_sec = pkts_sec_X100 / 100;
pkts_sec_100ths = pkts_sec_X100 % 100;
}
if (diff_us >= 1000 * 1000)
printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%02zd seconds\n",
stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)(diff.tv_usec / (10 * 1000)));
else
printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%06zd seconds\n",
stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)diff.tv_usec);
if (mb_sec >= 1)
printf("Rated: %llu.%1u Bps, %llu.%02u Mbps, %llu.%02u pps\n",
bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_100ths, pkts_sec, pkts_sec_100ths);
else
printf("Rated: %llu.%1u Bps, %llu.%03u Mbps, %llu.%02u pps\n",
bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_1000ths, pkts_sec, pkts_sec_100ths);
fflush(NULL);
if (stats->failed)
printf("Failed write attempts: " COUNTER_SPEC "\n",
stats->failed);
}
/**
* fills a buffer with a string representing the given time
*
* @param when: the time that should be formatted
* @param buf: a buffer to write to
* @param len: length of the buffer
* @return: string containing date, or -1 on error
*/
int format_date_time(struct timeval *when, char *buf, size_t len)
{
struct tm *tm;
char tmp[64];
assert(len);
tm = localtime(&when->tv_sec);
if (!tm)
return -1;
strftime(tmp, sizeof tmp, "%Y-%m-%d %H:%M:%S.%%06u", tm);
return snprintf(buf, len, tmp, when->tv_usec);
}
/**
* reads a hexstring in the format of xx,xx,xx,xx spits it back into *hex
* up to hexlen bytes. Returns actual number of bytes returned. On error
* it just calls errx() since all errors are fatal.
*/
int
read_hexstring(const char *l2string, u_char *hex, const int hexlen)
{
int numbytes = 0;
unsigned int value;
char *l2byte;
u_char databyte;
char *token = NULL;
char *string;
string = safe_strdup(l2string);
if (hexlen <= 0)
err(-1, "Hex buffer must be > 0");
memset(hex, '\0', hexlen);
/* data is hex, comma seperated, byte by byte */
/* get the first byte */
l2byte = strtok_r(string, ",", &token);
sscanf(l2byte, "%x", &value);
if (value > 0xff)
errx(-1, "Invalid hex string byte: %s", l2byte);
databyte = (u_char) value;
memcpy(&hex[numbytes], &databyte, 1);
/* get remaining bytes */
while ((l2byte = strtok_r(NULL, ",", &token)) != NULL) {
numbytes++;
if (numbytes + 1 > hexlen) {
warn("Hex buffer too small for data- skipping data");
goto done;
}
sscanf(l2byte, "%x", &value);
if (value > 0xff)
errx(-1, "Invalid hex string byte: %s", l2byte);
databyte = (u_char) value;
memcpy(&hex[numbytes], &databyte, 1);
}
numbytes++;
done:
safe_free(string);
dbgx(1, "Read %d bytes of hex data", numbytes);
return (numbytes);
}
#ifdef USE_CUSTOM_INET_ATON
int
inet_aton(const char *name, struct in_addr *addr)
{
in_addr_t a = inet_addr(name);
addr->s_addr = a;
return a != (in_addr_t)-1;
}
#endif
#if SIZEOF_LONG == 4
uint32_t __div64_32(uint64_t *n, uint32_t base)
{
uint64_t rem = *n;
uint64_t b = base;
uint64_t res, d = 1;
uint32_t high = rem >> 32;
/* Reduce the thing a bit first */
res = 0;
if (high >= base) {
high /= base;
res = (uint64_t) high << 32;
rem -= (uint64_t) (high*base) << 32;
}
while ((int64_t)b > 0 && b < rem) {
b = b+b;
d = d+d;
}
do {
if (rem >= b) {
rem -= b;
res += d;
}
b >>= 1;
d >>= 1;
} while (d);
*n = res;
return rem;
}
#endif /* SIZEOF_LONG == 4 */
/**
* Implementation of rand_r that is consistent across all platforms
* This algorithm is mentioned in the ISO C standard, here extended
* for 32 bits.
* @param: seed
* @return: random number
*/
uint32_t tcpr_random(uint32_t *seed)
{
unsigned int next = *seed;
int result;
next *= 1103515245;
next += 12345;
result = (unsigned int) (next / 65536) % 2048;
next *= 1103515245;
next += 12345;
result <<= 10;
result ^= (unsigned int) (next / 65536) % 1024;
next *= 1103515245;
next += 12345;
result <<= 10;
result ^= (unsigned int) (next / 65536) % 1024;
*seed = next;
return result;
}
/**
* #416 - Ensure STDIN is not left in non-blocking mode after closing
* a program. BSD and Unix derivatives should utilize `FIONBIO` due to known
* issues with reading from tty with a 0 byte read returning -1 opposed to 0.
*/
void restore_stdin(void)
{
#ifdef FIONBIO
int nb = 0;
ioctl(0, FIONBIO, &nb);
#else
fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
#endif /* FIONBIO */
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_508_2 |
crossvul-cpp_data_good_4216_0 | /*
* openvpn.c
*
* Copyright (C) 2011-20 - ntop.org
*
* OpenVPN TCP / UDP Detection - 128/160 hmac
*
* Detection based upon these openvpn protocol properties:
* - opcode
* - packet ID
* - session ID
*
* Two (good) packets are needed to perform detection.
* - First packet from client: save session ID
* - Second packet from server: report saved session ID
*
* TODO
* - Support PSK only mode (instead of TLS)
* - Support PSK + TLS mode (PSK used for early authentication)
* - TLS certificate extraction
*
*/
#include "ndpi_protocol_ids.h"
#define NDPI_CURRENT_PROTO NDPI_PROTOCOL_OPENVPN
#include "ndpi_api.h"
#define P_CONTROL_HARD_RESET_CLIENT_V1 (0x01 << 3)
#define P_CONTROL_HARD_RESET_CLIENT_V2 (0x07 << 3)
#define P_CONTROL_HARD_RESET_SERVER_V1 (0x02 << 3)
#define P_CONTROL_HARD_RESET_SERVER_V2 (0x08 << 3)
#define P_OPCODE_MASK 0xF8
#define P_SHA1_HMAC_SIZE 20
#define P_HMAC_128 16 // (RSA-)MD5, (RSA-)MD4, ..others
#define P_HMAC_160 20 // (RSA-|DSA-)SHA(1), ..others, SHA1 is openvpn default
#define P_HARD_RESET_PACKET_ID_OFFSET(hmac_size) (9 + hmac_size)
#define P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size) (P_HARD_RESET_PACKET_ID_OFFSET(hmac_size) + 8)
#define P_HARD_RESET_CLIENT_MAX_COUNT 5
static
#ifndef WIN32
inline
#endif
u_int32_t get_packet_id(const u_int8_t * payload, u_int8_t hms) {
return(ntohl(*(u_int32_t*)(payload + P_HARD_RESET_PACKET_ID_OFFSET(hms))));
}
static
#ifndef WIN32
inline
#endif
int8_t check_pkid_and_detect_hmac_size(const u_int8_t * payload) {
// try to guess
if(get_packet_id(payload, P_HMAC_160) == 1)
return P_HMAC_160;
if(get_packet_id(payload, P_HMAC_128) == 1)
return P_HMAC_128;
return(-1);
}
void ndpi_search_openvpn(struct ndpi_detection_module_struct* ndpi_struct,
struct ndpi_flow_struct* flow) {
struct ndpi_packet_struct* packet = &flow->packet;
const u_int8_t * ovpn_payload = packet->payload;
const u_int8_t * session_remote;
u_int8_t opcode;
u_int8_t alen;
int8_t hmac_size;
int8_t failed = 0;
/* No u_ */int16_t ovpn_payload_len = packet->payload_packet_len;
if(ovpn_payload_len >= 40) {
// skip openvpn TCP transport packet size
if(packet->tcp != NULL)
ovpn_payload += 2, ovpn_payload_len -= 2;;
opcode = ovpn_payload[0] & P_OPCODE_MASK;
if(packet->udp) {
#ifdef DEBUG
printf("[packet_id: %u][opcode: %u][Packet ID: %d][%u <-> %u][len: %u]\n",
flow->num_processed_pkts,
opcode, check_pkid_and_detect_hmac_size(ovpn_payload),
htons(packet->udp->source), htons(packet->udp->dest), ovpn_payload_len);
#endif
if(
(flow->num_processed_pkts == 1)
&& (
((ovpn_payload_len == 112)
&& ((opcode == 168) || (opcode == 192))
)
|| ((ovpn_payload_len == 80)
&& ((opcode == 184) || (opcode == 88) || (opcode == 160) || (opcode == 168) || (opcode == 200)))
)) {
NDPI_LOG_INFO(ndpi_struct,"found openvpn\n");
ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);
return;
}
}
if(flow->ovpn_counter < P_HARD_RESET_CLIENT_MAX_COUNT && (opcode == P_CONTROL_HARD_RESET_CLIENT_V1 ||
opcode == P_CONTROL_HARD_RESET_CLIENT_V2)) {
if(check_pkid_and_detect_hmac_size(ovpn_payload) > 0) {
memcpy(flow->ovpn_session_id, ovpn_payload+1, 8);
NDPI_LOG_DBG2(ndpi_struct,
"session key: %02x%02x%02x%02x%02x%02x%02x%02x\n",
flow->ovpn_session_id[0], flow->ovpn_session_id[1], flow->ovpn_session_id[2], flow->ovpn_session_id[3],
flow->ovpn_session_id[4], flow->ovpn_session_id[5], flow->ovpn_session_id[6], flow->ovpn_session_id[7]);
}
} else if(flow->ovpn_counter >= 1 && flow->ovpn_counter <= P_HARD_RESET_CLIENT_MAX_COUNT &&
(opcode == P_CONTROL_HARD_RESET_SERVER_V1 || opcode == P_CONTROL_HARD_RESET_SERVER_V2)) {
hmac_size = check_pkid_and_detect_hmac_size(ovpn_payload);
if(hmac_size > 0) {
u_int16_t offset = P_PACKET_ID_ARRAY_LEN_OFFSET(hmac_size);
alen = ovpn_payload[offset];
if (alen > 0) {
offset += 1 + alen * 4;
if((offset+8) <= ovpn_payload_len) {
session_remote = &ovpn_payload[offset];
if(memcmp(flow->ovpn_session_id, session_remote, 8) == 0) {
NDPI_LOG_INFO(ndpi_struct,"found openvpn\n");
ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_OPENVPN, NDPI_PROTOCOL_UNKNOWN);
return;
} else {
NDPI_LOG_DBG2(ndpi_struct,
"key mismatch: %02x%02x%02x%02x%02x%02x%02x%02x\n",
session_remote[0], session_remote[1], session_remote[2], session_remote[3],
session_remote[4], session_remote[5], session_remote[6], session_remote[7]);
failed = 1;
}
} else
failed = 1;
} else
failed = 1;
} else
failed = 1;
} else
failed = 1;
flow->ovpn_counter++;
if(failed) {
NDPI_EXCLUDE_PROTO(ndpi_struct, flow);
}
}
}
void init_openvpn_dissector(struct ndpi_detection_module_struct *ndpi_struct,
u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) {
ndpi_set_bitmask_protocol_detection("OpenVPN", ndpi_struct, detection_bitmask, *id,
NDPI_PROTOCOL_OPENVPN,
ndpi_search_openvpn,
NDPI_SELECTION_BITMASK_PROTOCOL_TCP_OR_UDP_WITH_PAYLOAD,
SAVE_DETECTION_BITMASK_AS_UNKNOWN,
ADD_TO_DETECTION_BITMASK);
*id += 1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4216_0 |
crossvul-cpp_data_good_2723_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(*tptr);
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:
ND_PRINT((ndo, "[|esis]"));
}
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;
int sysid_len;
sysid_len = SYSTEM_ID_LEN;
if (sysid_len > id_len)
sysid_len = id_len;
for (i = 1; i <= sysid_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_2723_0 |
crossvul-cpp_data_bad_140_1 | /* radare - LGPL - Copyright 2011-2018 - earada, pancake */
#include <r_core.h>
#include "r_util.h"
#define DBSPATH "/share/radare2/" R2_VERSION "/fcnsign"
#define is_in_range(at, from, sz) ((at) >= (from) && (at) < ((from) + (sz)))
#define VA_FALSE 0
#define VA_TRUE 1
#define VA_NOREBASE 2
#define IS_MODE_SET(mode) (mode & R_CORE_BIN_SET)
#define IS_MODE_SIMPLE(mode) (mode & R_CORE_BIN_SIMPLE)
#define IS_MODE_SIMPLEST(mode) (mode & R_CORE_BIN_SIMPLEST)
#define IS_MODE_JSON(mode) (mode & R_CORE_BIN_JSON)
#define IS_MODE_RAD(mode) (mode & R_CORE_BIN_RADARE)
#define IS_MODE_NORMAL(mode) (!mode)
#define IS_MODE_CLASSDUMP(mode) (mode & R_CORE_BIN_CLASSDUMP)
// dup from cmd_info
#define PAIR_WIDTH 9
static void pair(const char *a, const char *b, int mode, bool last) {
if (!b || !*b) {
return;
}
if (IS_MODE_JSON (mode)) {
const char *lst = last ? "" : ",";
r_cons_printf ("\"%s\":%s%s", a, b, lst);
} else {
char ws[16];
int al = strlen (a);
if (al > PAIR_WIDTH) {
al = 0;
} else {
al = PAIR_WIDTH - al;
}
memset (ws, ' ', al);
ws[al] = 0;
r_cons_printf ("%s%s%s\n", a, ws, b);
}
}
static void pair_bool(const char *a, bool t, int mode, bool last) {
pair (a, r_str_bool (t), mode, last);
}
static void pair_int(const char *a, int n, int mode, bool last) {
pair (a, sdb_fmt ("%d", n), mode, last);
}
static void pair_ut64(const char *a, ut64 n, int mode, bool last) {
pair (a, sdb_fmt ("%"PFMT64d, n), mode, last);
}
static void pair_str(const char *a, const char *b, int mode, int last) {
if (IS_MODE_JSON (mode)) {
if (!b) {
b = "";
}
char *eb = r_str_utf16_encode (b, -1);
if (eb) {
char *qs = r_str_newf ("\"%s\"", eb);
pair (a, qs, mode, last);
free (eb);
free (qs);
}
} else {
pair (a, b, mode, last);
}
}
#define STR(x) (x)?(x):""
R_API int r_core_bin_set_cur (RCore *core, RBinFile *binfile);
static ut64 rva(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
if (va == VA_TRUE) {
return r_bin_get_vaddr (bin, paddr, vaddr);
}
if (va == VA_NOREBASE) {
return vaddr;
}
return paddr;
}
R_API int r_core_bin_set_by_fd(RCore *core, ut64 bin_fd) {
if (r_bin_file_set_cur_by_fd (core->bin, bin_fd)) {
r_core_bin_set_cur (core, r_core_bin_cur (core));
return true;
}
return false;
}
R_API int r_core_bin_set_by_name(RCore *core, const char * name) {
if (r_bin_file_set_cur_by_name (core->bin, name)) {
r_core_bin_set_cur (core, r_core_bin_cur (core));
return true;
}
return false;
}
R_API int r_core_bin_set_env(RCore *r, RBinFile *binfile) {
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
if (info) {
int va = info->has_va;
const char * arch = info->arch;
ut16 bits = info->bits;
ut64 baseaddr = r_bin_get_baddr (r->bin);
r_config_set_i (r->config, "bin.baddr", baseaddr);
r_config_set (r->config, "asm.arch", arch);
r_config_set_i (r->config, "asm.bits", bits);
r_config_set (r->config, "anal.arch", arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "anal.cpu", info->cpu);
} else {
r_config_set (r->config, "anal.cpu", arch);
}
r_asm_use (r->assembler, arch);
r_core_bin_info (r, R_CORE_BIN_ACC_ALL, R_CORE_BIN_SET, va, NULL, NULL);
r_core_bin_set_cur (r, binfile);
return true;
}
return false;
}
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile) {
if (!core->bin) {
return false;
}
if (!binfile) {
// Find first available binfile
ut32 fd = r_core_file_cur_fd (core);
binfile = fd != (ut32)-1
? r_bin_file_find_by_fd (core->bin, fd)
: NULL;
if (!binfile) {
return false;
}
}
r_bin_file_set_cur_binfile (core->bin, binfile);
return true;
}
R_API int r_core_bin_refresh_strings(RCore *r) {
return r_bin_reset_strings (r->bin) ? true: false;
}
R_API RBinFile * r_core_bin_cur(RCore *core) {
RBinFile *binfile = r_bin_cur (core->bin);
return binfile;
}
static void _print_strings(RCore *r, RList *list, int mode, int va) {
bool b64str = r_config_get_i (r->config, "bin.b64str");
int minstr = r_config_get_i (r->config, "bin.minstr");
int maxstr = r_config_get_i (r->config, "bin.maxstr");
RBin *bin = r->bin;
RBinObject *obj = r_bin_cur_object (bin);
RListIter *iter;
RListIter *last_processed = NULL;
RBinString *string;
RBinSection *section;
char *q;
bin->minstrlen = minstr;
bin->maxstrlen = maxstr;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs strings");
}
if (IS_MODE_SET (mode) && r_config_get_i (r->config, "bin.strings")) {
r_flag_space_set (r->flags, "strings");
r_cons_break_push (NULL, NULL);
}
RBinString b64 = {0};
r_list_foreach (list, iter, string) {
const char *section_name, *type_string;
ut64 paddr, vaddr, addr;
paddr = string->paddr;
vaddr = r_bin_get_vaddr (bin, paddr, string->vaddr);
addr = va ? vaddr : paddr;
if (!r_bin_string_filter (bin, string->string, addr)) {
continue;
}
if (string->length < minstr) {
continue;
}
if (maxstr && string->length > maxstr) {
continue;
}
section = r_bin_get_section_at (obj, paddr, 0);
section_name = section ? section->name : "";
type_string = r_bin_string_type (string->type);
if (b64str) {
ut8 *s = r_base64_decode_dyn (string->string, -1);
if (s && *s && IS_PRINTABLE (*s)) {
// TODO: add more checks
free (b64.string);
memcpy (&b64, string, sizeof (b64));
b64.string = (char *)s;
b64.size = strlen (b64.string);
string = &b64;
}
}
if (IS_MODE_SET (mode)) {
char *f_name, *str;
if (r_cons_is_breaked ()) {
break;
}
r_meta_add (r->anal, R_META_TYPE_STRING, addr, addr + string->size, string->string);
f_name = strdup (string->string);
r_name_filter (f_name, -1);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
} else {
str = r_str_newf ("str.%s", f_name);
}
r_flag_set (r->flags, str, addr, string->size);
free (str);
free (f_name);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%"PFMT64x" %d %d %s\n", addr,
string->size, string->length, string->string);
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_println (string->string);
} else if (IS_MODE_JSON (mode)) {
int *block_list;
q = r_base64_encode_dyn (string->string, -1);
r_cons_printf ("%s{\"vaddr\":%"PFMT64d
",\"paddr\":%"PFMT64d",\"ordinal\":%d"
",\"size\":%d,\"length\":%d,\"section\":\"%s\","
"\"type\":\"%s\",\"string\":\"%s\"",
last_processed ? ",": "",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, q);
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't include block list if
just Basic Latin (0x00 - 0x7F) */
break;
}
int *block_ptr = block_list;
r_cons_printf (",\"blocks\":[");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *utfName = r_utf_block_name (*block_ptr);
r_cons_printf ("\"%s\"", utfName? utfName: "");
}
r_cons_printf ("]");
R_FREE (block_list);
}
}
r_cons_printf ("}");
free (q);
} else if (IS_MODE_RAD (mode)) {
char *f_name, *str;
f_name = strdup (string->string);
r_name_filter (f_name, R_FLAG_NAME_SIZE);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
r_cons_printf ("f %s.str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
r->bin->prefix, f_name, string->size, addr,
string->size, addr);
} else {
str = r_str_newf ("str.%s", f_name);
r_cons_printf ("f str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
f_name, string->size, addr,
string->size, addr);
}
free (str);
free (f_name);
} else {
int *block_list;
char *str = string->string;
char *no_dbl_bslash_str = NULL;
if (!r->print->esc_bslash) {
char *ptr;
for (ptr = str; *ptr; ptr++) {
if (*ptr != '\\') {
continue;
}
if (*(ptr + 1) == '\\') {
if (!no_dbl_bslash_str) {
no_dbl_bslash_str = strdup (str);
if (!no_dbl_bslash_str) {
break;
}
ptr = no_dbl_bslash_str + (ptr - str);
}
memmove (ptr + 1, ptr + 2, strlen (ptr + 2) + 1);
}
}
if (no_dbl_bslash_str) {
str = no_dbl_bslash_str;
}
}
#if 0
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"
PFMT64x" ordinal=%03u sz=%u len=%u "
"section=%s type=%s string=%s",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, str);
#else
r_cons_printf ("%03u 0x%08"PFMT64x" 0x%08"
PFMT64x" %3u %3u "
"(%s) %5s %s",
string->ordinal, paddr, vaddr,
string->length, string->size,
section_name, type_string, str);
#endif
if (str == no_dbl_bslash_str) {
R_FREE (str);
}
switch (string->type) {
case R_STRING_TYPE_UTF8:
case R_STRING_TYPE_WIDE:
case R_STRING_TYPE_WIDE32:
block_list = r_utf_block_list ((const ut8*)string->string);
if (block_list) {
if (block_list[0] == 0 && block_list[1] == -1) {
/* Don't show block list if
just Basic Latin (0x00 - 0x7F) */
break;
}
int *block_ptr = block_list;
r_cons_printf (" blocks=");
for (; *block_ptr != -1; block_ptr++) {
if (block_ptr != block_list) {
r_cons_printf (",");
}
const char *name = r_utf_block_name (*block_ptr);
r_cons_printf ("%s", name? name: "");
}
free (block_list);
}
break;
}
r_cons_printf ("\n");
}
last_processed = iter;
}
R_FREE (b64.string);
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
}
if (IS_MODE_SET (mode)) {
r_cons_break_pop ();
}
}
static bool bin_raw_strings(RCore *r, int mode, int va) {
RBinFile *bf = r_bin_cur (r->bin);
bool new_bf = false;
if (bf && strstr (bf->file, "malloc://")) {
//sync bf->buf to search string on it
r_io_read_at (r->io, 0, bf->buf->buf, bf->size);
}
if (!r->file) {
eprintf ("Core file not open\n");
return false;
}
if (!bf) {
bf = R_NEW0 (RBinFile);
if (!bf) {
return false;
}
RIODesc *desc = r_io_desc_get (r->io, r->file->fd);
if (!desc) {
free (bf);
return false;
}
bf->file = strdup (desc->name);
bf->size = r_io_desc_size (desc);
if (bf->size == UT64_MAX) {
free (bf);
return false;
}
bf->buf = r_buf_new_with_io (&r->bin->iob, r->file->fd);
#if 0
bf->buf = r_buf_new ();
if (!bf->buf) {
free (bf);
return false;
}
bf->buf->buf = malloc (bf->size);
if (!bf->buf->buf) {
free (bf->buf);
free (bf);
return false;
}
bf->buf->fd = r->file->fd;
bf->buf->length = bf->size;
r_io_read_at (r->io, 0, bf->buf->buf, bf->size);
#endif
bf->o = NULL;
bf->rbin = r->bin;
new_bf = true;
va = false;
}
RList *l = r_bin_raw_strings (bf, 0);
_print_strings (r, l, mode, va);
if (new_bf) {
r_buf_free (bf->buf);
bf->buf = NULL;
bf->id = -1;
r_bin_file_free (bf);
}
return true;
}
static bool bin_strings(RCore *r, int mode, int va) {
RList *list;
RBinFile *binfile = r_core_bin_cur (r);
RBinPlugin *plugin = r_bin_file_cur_plugin (binfile);
int rawstr = r_config_get_i (r->config, "bin.rawstr");
if (!binfile) {
return false;
}
if (!r_config_get_i (r->config, "bin.strings")) {
return false;
}
if (!plugin) {
return false;
}
if (plugin->info && plugin->name) {
if (strcmp (plugin->name, "any") == 0 && !rawstr) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
}
if (!(list = r_bin_get_strings (r->bin))) {
return false;
}
_print_strings (r, list, mode, va);
return true;
}
static const char* get_compile_time(Sdb *binFileSdb) {
Sdb *info_ns = sdb_ns (binFileSdb, "info", false);
const char *timeDateStamp_string = sdb_const_get (info_ns,
"image_file_header.TimeDateStamp_string", 0);
return timeDateStamp_string;
}
static int is_executable(RBinObject *obj) {
RListIter *it;
RBinSection* sec;
if (obj) {
if (obj->info && obj->info->arch) {
return true;
}
r_list_foreach (obj->sections, it, sec) {
if (R_BIN_SCN_EXECUTABLE & sec->srwx) {
return true;
}
}
}
return false;
}
static void sdb_concat_by_path(Sdb *s, const char *path) {
Sdb *db = sdb_new (0, path, 0);
sdb_merge (s, db);
sdb_close (db);
sdb_free (db);
}
R_API void r_core_anal_type_init(RCore *core) {
Sdb *types = NULL;
const char *anal_arch = NULL, *os = NULL;
char *dbpath;
if (!core || !core->anal) {
return;
}
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
int bits = core->assembler->bits;
types = core->anal->sdb_types;
// make sure they are empty this is initializing
sdb_reset (types);
anal_arch = r_config_get (core->config, "anal.arch");
os = r_config_get (core->config, "asm.os");
// spaguetti ahead
dbpath = sdb_fmt ("%s/"DBSPATH"/types.sdb", dir_prefix);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s.sdb", dir_prefix, anal_arch);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s.sdb", dir_prefix, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%d.sdb", dir_prefix, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%d.sdb", dir_prefix, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%d.sdb", dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%s.sdb", dir_prefix, anal_arch, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt ("%s/"DBSPATH"/types-%s-%s-%d.sdb", dir_prefix, anal_arch, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
}
static int save_ptr(void *p, const char *k, const char *v) {
Sdb *sdbs[2];
sdbs[0] = ((Sdb**) p)[0];
sdbs[1] = ((Sdb**) p)[1];
if (!strncmp (v, "cc", strlen ("cc") + 1)) {
const char *x = sdb_const_get (sdbs[1], sdb_fmt ("cc.%s.name", k), 0);
char *tmp = sdb_fmt ("%p", x);
sdb_set (sdbs[0], tmp, x, 0);
}
return 1;
}
R_API void r_core_anal_cc_init(RCore *core) {
Sdb *sdbs[2] = {
sdb_new0 (),
core->anal->sdb_cc
};
const char *dir_prefix = r_config_get (core->config, "dir.prefix");
//save pointers and values stored inside them
//to recover from freeing heeps
const char *defaultcc = sdb_const_get (sdbs[1], "default.cc", 0);
sdb_set (sdbs[0], sdb_fmt ("0x%08"PFMT64x, r_num_get (NULL, defaultcc)), defaultcc, 0);
sdb_foreach (core->anal->sdb_cc, save_ptr, sdbs);
sdb_reset ( core->anal->sdb_cc);
const char *anal_arch = r_config_get (core->config, "anal.arch");
int bits = core->anal->bits;
if (bits == 16 && !strcmp (anal_arch, "arm")) {
bits = 32;
}
char *dbpath = sdb_fmt ("%s/"DBSPATH"/cc-%s-%d.sdb", dir_prefix, anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (core->anal->sdb_cc, dbpath);
}
//restore all freed CC or replace with new default cc
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
char *ptr = sdb_fmt ("%p", fcn->cc);
const char *cc = sdb_const_get (sdbs[0], ptr, 0);
if (cc) {
fcn->cc = r_anal_cc_to_constant (core->anal, (char *)cc);
}
if (!fcn->cc) {
fcn->cc = r_anal_cc_default (core->anal);
}
fcn->cc = r_str_const (fcn->cc);
}
sdb_close (sdbs[0]);
sdb_free (sdbs[0]);
}
#undef DBSPATH
static int bin_info(RCore *r, int mode) {
int i, j, v;
char str[R_FLAG_NAME_SIZE];
RBinInfo *info = r_bin_get_info (r->bin);
RBinFile *binfile = r_core_bin_cur (r);
RBinObject *obj = r_bin_cur_object (r->bin);
const char *compiled = NULL;
bool havecode;
if (!binfile || !info || !obj) {
if (mode & R_CORE_BIN_JSON) {
r_cons_printf ("{}");
}
return false;
}
havecode = is_executable (obj) | (obj->entries != NULL);
compiled = get_compile_time (binfile->sdb);
if (IS_MODE_SET (mode)) {
r_config_set (r->config, "file.type", info->rclass);
r_config_set (r->config, "cfg.bigendian",
info->big_endian ? "true" : "false");
if (info->rclass && !strcmp (info->rclass, "fs")) {
// r_config_set (r->config, "asm.arch", info->arch);
// r_core_seek (r, 0, 1);
// eprintf ("m /root %s 0", info->arch);
// r_core_cmdf (r, "m /root hfs @ 0", info->arch);
} else {
if (info->lang) {
r_config_set (r->config, "bin.lang", info->lang);
}
r_config_set (r->config, "asm.os", info->os);
if (info->rclass && !strcmp (info->rclass, "pe")) {
r_config_set (r->config, "anal.cpp.abi", "msvc");
} else {
r_config_set (r->config, "anal.cpp.abi", "itanium");
}
r_config_set (r->config, "asm.arch", info->arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "asm.cpu", info->cpu);
}
r_config_set (r->config, "anal.arch", info->arch);
snprintf (str, R_FLAG_NAME_SIZE, "%i", info->bits);
r_config_set (r->config, "asm.bits", str);
r_config_set (r->config, "asm.dwarf",
(R_BIN_DBG_STRIPPED & info->dbg_info) ? "false" : "true");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) r_config_set_i (r->config, "asm.pcalign", v);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("arch %s\n", info->arch);
if (info->cpu && *info->cpu) {
r_cons_printf ("cpu %s\n", info->cpu);
}
r_cons_printf ("bits %d\n", info->bits);
r_cons_printf ("os %s\n", info->os);
r_cons_printf ("endian %s\n", info->big_endian? "big": "little");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
r_cons_printf ("minopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
r_cons_printf ("maxopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("pcalign %d\n", v);
}
} else if (IS_MODE_RAD (mode)) {
if (info->type && !strcmp (info->type, "fs")) {
r_cons_printf ("e file.type=fs\n");
r_cons_printf ("m /root %s 0\n", info->arch);
} else {
r_cons_printf ("e cfg.bigendian=%s\n"
"e asm.bits=%i\n"
"e asm.dwarf=%s\n",
r_str_bool (info->big_endian),
info->bits,
r_str_bool (R_BIN_DBG_STRIPPED &info->dbg_info));
if (info->lang && *info->lang) {
r_cons_printf ("e bin.lang=%s\n", info->lang);
}
if (info->rclass && *info->rclass) {
r_cons_printf ("e file.type=%s\n",
info->rclass);
}
if (info->os) {
r_cons_printf ("e asm.os=%s\n", info->os);
}
if (info->arch) {
r_cons_printf ("e asm.arch=%s\n", info->arch);
}
if (info->cpu && *info->cpu) {
r_cons_printf ("e asm.cpu=%s\n", info->cpu);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) r_cons_printf ("e asm.pcalign=%d\n", v);
}
} else {
// XXX: if type is 'fs' show something different?
char *tmp_buf;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{");
}
pair_str ("arch", info->arch, mode, false);
if (info->cpu && *info->cpu) {
pair_str ("cpu", info->cpu, mode, false);
}
pair_ut64 ("binsz", r_bin_get_size (r->bin), mode, false);
pair_str ("bintype", info->rclass, mode, false);
pair_int ("bits", info->bits, mode, false);
pair_bool ("canary", info->has_canary, mode, false);
pair_str ("class", info->bclass, mode, false);
if (info->actual_checksum) {
/* computed checksum */
pair_str ("cmp.csum", info->actual_checksum, mode, false);
}
pair_str ("compiled", compiled, mode, false);
pair_bool ("crypto", info->has_crypto, mode, false);
pair_str ("dbg_file", info->debug_file_name, mode, false);
pair_str ("endian", info->big_endian ? "big" : "little", mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
tmp_buf = sdb_get (binfile->sdb, "mdmp.flags", 0);
if (tmp_buf) {
pair_str ("flags", tmp_buf, mode, false);
free (tmp_buf);
}
}
pair_bool ("havecode", havecode, mode, false);
if (info->claimed_checksum) {
/* checksum specified in header */
pair_str ("hdr.csum", info->claimed_checksum, mode, false);
}
pair_str ("guid", info->guid, mode, false);
pair_str ("intrp", info->intrp, mode, false);
pair_str ("lang", info->lang, mode, false);
pair_bool ("linenum", R_BIN_DBG_LINENUMS & info->dbg_info, mode, false);
pair_bool ("lsyms", R_BIN_DBG_SYMS & info->dbg_info, mode, false);
pair_str ("machine", info->machine, mode, false);
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
pair_int ("maxopsz", v, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
pair_int ("minopsz", v, mode, false);
}
pair_bool ("nx", info->has_nx, mode, false);
pair_str ("os", info->os, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
pair_bool ("overlay", info->pe_overlay, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
pair_int ("pcalign", v, mode, false);
}
pair_bool ("pic", info->has_pi, mode, false);
pair_bool ("relocs", R_BIN_DBG_RELOCS & info->dbg_info, mode, false);
tmp_buf = sdb_get (obj->kv, "elf.relro", 0);
if (tmp_buf) {
pair_str ("relro", tmp_buf, mode, false);
free (tmp_buf);
}
pair_str ("rpath", info->rpath, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
//this should be moved if added to mach0 (or others)
pair_bool ("signed", info->signature, mode, false);
}
pair_bool ("static", r_bin_is_static (r->bin), mode, false);
if (info->rclass && !strcmp (info->rclass, "mdmp")) {
v = sdb_num_get (binfile->sdb, "mdmp.streams", 0);
if (v != -1) {
pair_int ("streams", v, mode, false);
}
}
pair_bool ("stripped", R_BIN_DBG_STRIPPED & info->dbg_info, mode, false);
pair_str ("subsys", info->subsystem, mode, false);
pair_bool ("va", info->has_va, mode, true);
if (IS_MODE_JSON (mode)) {
r_cons_printf (",\"checksums\":{");
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
int len = r_hash_calculate (rh, hash, (const ut8*)
binfile->buf->buf+h->from, h->to);
if (len < 1) {
eprintf ("Invaild checksum length\n");
}
r_hash_free (rh);
r_cons_printf ("%s\"%s\":{\"hex\":\"", i?",": "", h->type);
// r_cons_printf ("%s\t%d-%dc\t", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_printf ("\"}");
}
r_cons_printf ("}");
} else {
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
int len = r_hash_calculate (rh, hash, (const ut8*)
binfile->buf->buf+h->from, h->to);
if (len < 1) {
eprintf ("Invaild wtf\n");
}
r_hash_free (rh);
r_cons_printf ("%s %d-%dc ", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_newline ();
}
}
if (IS_MODE_JSON (mode)) r_cons_printf ("}");
}
r_core_anal_type_init (r);
r_core_anal_cc_init (r);
return true;
}
static int bin_dwarf(RCore *core, int mode) {
RBinDwarfRow *row;
RListIter *iter;
RList *list = NULL;
if (!r_config_get_i (core->config, "bin.dbginfo")) {
return false;
}
RBinFile *binfile = r_core_bin_cur (core);
RBinPlugin * plugin = r_bin_file_cur_plugin (binfile);
if (!binfile) {
return false;
}
if (plugin && plugin->lines) {
list = plugin->lines (binfile);
} else if (core->bin) {
// TODO: complete and speed-up support for dwarf
RBinDwarfDebugAbbrev *da = NULL;
da = r_bin_dwarf_parse_abbrev (core->bin, mode);
r_bin_dwarf_parse_info (da, core->bin, mode);
r_bin_dwarf_parse_aranges (core->bin, mode);
list = r_bin_dwarf_parse_line (core->bin, mode);
r_bin_dwarf_free_debug_abbrev (da);
free (da);
}
if (!list) {
return false;
}
r_cons_break_push (NULL, NULL);
/* cache file:line contents */
const char *lastFile = NULL;
int *lastFileLines = NULL;
char *lastFileContents = NULL;
int lastFileLinesCount = 0;
/* ugly dupe for speedup */
const char *lastFile2 = NULL;
int *lastFileLines2 = NULL;
char *lastFileContents2 = NULL;
int lastFileLinesCount2 = 0;
const char *lf = NULL;
int *lfl = NULL;
char *lfc = NULL;
int lflc = 0;
//TODO we should need to store all this in sdb, or do a filecontentscache in libr/util
//XXX this whole thing has leaks
r_list_foreach (list, iter, row) {
if (r_cons_is_breaked ()) {
break;
}
if (mode) {
// TODO: use 'Cl' instead of CC
const char *path = row->file;
if (!lastFile || strcmp (path, lastFile)) {
if (lastFile && lastFile2 && !strcmp (path, lastFile2)) {
lf = lastFile;
lfl = lastFileLines;
lfc = lastFileContents;
lflc = lastFileLinesCount;
lastFile = lastFile2;
lastFileLines = lastFileLines2;
lastFileContents = lastFileContents2;
lastFileLinesCount = lastFileLinesCount2;
lastFile2 = lf;
lastFileLines2 = lfl;
lastFileContents2 = lfc;
lastFileLinesCount2 = lflc;
} else {
lastFile2 = lastFile;
lastFileLines2 = lastFileLines;
lastFileContents2 = lastFileContents;
lastFileLinesCount2 = lastFileLinesCount;
lastFile = path;
lastFileContents = r_file_slurp (path, NULL);
if (lastFileContents) {
lastFileLines = r_str_split_lines (lastFileContents, &lastFileLinesCount);
}
}
}
char *line = NULL;
//r_file_slurp_line (path, row->line - 1, 0);
if (lastFileLines && lastFileContents) {
int nl = row->line - 1;
if (nl >= 0 && nl < lastFileLinesCount) {
line = strdup (lastFileContents + lastFileLines[nl]);
}
} else {
line = NULL;
}
if (line) {
r_str_filter (line, strlen (line));
line = r_str_replace (line, "\"", "\\\"", 1);
line = r_str_replace (line, "\\\\", "\\", 1);
}
bool chopPath = !r_config_get_i (core->config, "dir.dwarf.abspath");
char *file = strdup (row->file);
if (chopPath) {
const char *slash = r_str_lchr (file, '/');
if (slash) {
memmove (file, slash + 1, strlen (slash));
}
}
// TODO: implement internal : if ((mode & R_CORE_BIN_SET))
if ((mode & R_CORE_BIN_SET)) {
// TODO: use CL here.. but its not necessary.. so better not do anything imho
// r_core_cmdf (core, "CL %s:%d 0x%08"PFMT64x, file, (int)row->line, row->address);
#if 0
char *cmt = r_str_newf ("%s:%d %s", file, (int)row->line, line? line: "");
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, row->address, cmt);
free (cmt);
#endif
} else {
r_cons_printf ("CL %s:%d 0x%08" PFMT64x "\n",
file, (int)row->line,
row->address);
r_cons_printf ("\"CC %s:%d %s\"@0x%" PFMT64x
"\n",
file, row->line,
line ? line : "", row->address);
}
free (file);
free (line);
} else {
r_cons_printf ("0x%08" PFMT64x "\t%s\t%d\n",
row->address, row->file, row->line);
}
}
r_cons_break_pop ();
R_FREE (lastFileContents);
R_FREE (lastFileContents2);
// this list is owned by rbin, not us, we shouldnt free it
// r_list_free (list);
free (lastFileLines);
return true;
}
R_API int r_core_pdb_info(RCore *core, const char *file, ut64 baddr, int mode) {
R_PDB pdb = R_EMPTY;
pdb.cb_printf = r_cons_printf;
if (!init_pdb_parser (&pdb, file)) {
return false;
}
if (!pdb.pdb_parse (&pdb)) {
eprintf ("pdb was not parsed\n");
pdb.finish_pdb_parse (&pdb);
return false;
}
if (mode == R_CORE_BIN_JSON) {
r_cons_printf("[");
}
switch (mode) {
case R_CORE_BIN_SET:
mode = 's';
r_core_cmd0 (core, ".iP*");
return true;
case R_CORE_BIN_JSON:
mode = 'j';
break;
case '*':
case 1:
mode = 'r';
break;
default:
mode = 'd'; // default
break;
}
pdb.print_types (&pdb, mode);
if (mode == 'j') {
r_cons_printf (",");
}
pdb.print_gvars (&pdb, baddr, mode);
if (mode == 'j') {
r_cons_printf ("]");
}
pdb.finish_pdb_parse (&pdb);
return true;
}
static int bin_pdb(RCore *core, int mode) {
ut64 baddr = r_bin_get_baddr (core->bin);
return r_core_pdb_info (core, core->bin->file, baddr, mode);
}
static int bin_main(RCore *r, int mode, int va) {
RBinAddr *binmain = r_bin_get_sym (r->bin, R_BIN_SYM_MAIN);
ut64 addr;
if (!binmain) {
return false;
}
addr = va ? r_bin_a2b (r->bin, binmain->vaddr) : binmain->paddr;
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
r_flag_set (r->flags, "main", addr, r->blocksize);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("%"PFMT64d, addr);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
r_cons_printf ("f main @ 0x%08"PFMT64x"\n", addr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"vaddr\":%" PFMT64d
",\"paddr\":%" PFMT64d "}", addr, binmain->paddr);
} else {
r_cons_printf ("[Main]\n");
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x"\n",
addr, binmain->paddr);
}
return true;
}
static int bin_entry(RCore *r, int mode, ut64 laddr, int va, bool inifin) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
if (inifin) {
r_cons_printf ("[Constructors]\n");
} else {
r_cons_printf ("[Entrypoints]\n");
}
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (mode != R_CORE_BIN_SET) {
if (inifin) {
if (entry->type == R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
} else {
if (entry->type != R_BIN_ENTRY_TYPE_PROGRAM) {
continue;
}
}
}
switch (entry->type) {
case R_BIN_ENTRY_TYPE_INIT:
case R_BIN_ENTRY_TYPE_FINI:
case R_BIN_ENTRY_TYPE_PREINIT:
if (r->io->va && entry->paddr == entry->vaddr) {
RIOMap *map = r_io_map_get (r->io, entry->vaddr);
if (map) {
paddr = entry->vaddr - map->itv.addr + map->delta;
}
}
}
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i.preinit", i);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
}
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
char *name = NULL;
if (entry->type == R_BIN_ENTRY_TYPE_INIT) {
name = r_str_newf ("entry%i.init", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_FINI) {
name = r_str_newf ("entry%i.fini", i);
} else if (entry->type == R_BIN_ENTRY_TYPE_PREINIT) {
name = r_str_newf ("entry%i.preinit", i);
} else {
name = r_str_newf ("entry%i", i);
}
r_cons_printf ("f %s 1 @ 0x%08"PFMT64x"\n", name, at);
r_cons_printf ("f %s_haddr 1 @ 0x%08"PFMT64x"\n", name, haddr);
r_cons_printf ("s %s\n", name);
free (name);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
static const char *bin_reloc_type_name(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return reloc->additive ? "ADD_" #T : "SET_" #T
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return "UNKNOWN";
#undef CASE
}
static ut8 bin_reloc_size(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return T / 8
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return 0;
#undef CASE
}
static char *resolveModuleOrdinal(Sdb *sdb, const char *module, int ordinal) {
Sdb *db = sdb;
char *foo = sdb_get (db, sdb_fmt ("%d", ordinal), 0);
return (foo && *foo) ? foo : NULL;
}
static char *get_reloc_name(RBinReloc *reloc, ut64 addr) {
char *reloc_name = NULL;
if (reloc->import && reloc->import->name) {
reloc_name = sdb_fmt ("reloc.%s_%d", reloc->import->name,
(int)(addr & 0xff));
if (!reloc_name) {
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->symbol && reloc->symbol->name) {
reloc_name = sdb_fmt ("reloc.%s_%d", reloc->symbol->name, (int)(addr & 0xff));
if (!reloc_name) {
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->is_ifunc) {
// addend is the function pointer for the resolving ifunc
reloc_name = sdb_fmt ("reloc.ifunc_%"PFMT64x, reloc->addend);
} else {
// TODO(eddyb) implement constant relocs.
}
return reloc_name;
}
static void set_bin_relocs(RCore *r, RBinReloc *reloc, ut64 addr, Sdb **db, char **sdb_module) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
const char *lang = r_config_get (r->config, "bin.lang");
char *reloc_name, *demname = NULL;
bool is_pe = true;
int is_sandbox = r_sandbox_enable (0);
if (reloc->import && reloc->import->name[0]) {
char str[R_FLAG_NAME_SIZE];
RFlagItem *fi;
if (is_pe && !is_sandbox && strstr (reloc->import->name, "Ordinal")) {
const char *TOKEN = ".dll_Ordinal_";
char *module = strdup (reloc->import->name);
char *import = strstr (module, TOKEN);
r_str_case (module, false);
if (import) {
char *filename = NULL;
int ordinal;
*import = 0;
import += strlen (TOKEN);
ordinal = atoi (import);
if (!*sdb_module || strcmp (module, *sdb_module)) {
sdb_free (*db);
*db = NULL;
free (*sdb_module);
*sdb_module = strdup (module);
/* always lowercase */
filename = sdb_fmt ("%s.sdb", module);
r_str_case (filename, false);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
} else {
// XXX. we have dir.prefix, windows shouldnt work different
filename = sdb_fmt ("%s/share/radare2/" R2_VERSION"/format/dll/%s.sdb", r_config_get (r->config, "dir.prefix"), module);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
#if __WINDOWS__
} else {
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, module);
} else {
filename = sdb_fmt ("share/radare2/"R2_VERSION"/format/dll/%s.sdb", module);
}
#else
filename = sdb_fmt ("%s/share/radare2/" R2_VERSION"/format/dll/%s.sdb", r_config_get (r->config, "dir.prefix"), module);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
}
#endif
}
}
}
if (*db) {
// ordinal-1 because we enumerate starting at 0
char *symname = resolveModuleOrdinal (*db, module, ordinal - 1); // uses sdb_get
if (symname) {
if (r->bin->prefix) {
reloc->import->name = r_str_newf
("%s.%s.%s", r->bin->prefix, module, symname);
} else {
reloc->import->name = r_str_newf
("%s.%s", module, symname);
}
R_FREE (symname);
}
}
}
free (module);
r_anal_hint_set_size (r->anal, reloc->vaddr, 4);
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr+4, NULL);
}
reloc_name = reloc->import->name;
if (r->bin->prefix) {
snprintf (str, R_FLAG_NAME_SIZE, "%s.reloc.%s", r->bin->prefix, reloc_name);
} else {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s", reloc_name);
}
if (bin_demangle) {
demname = r_bin_demangle (r->bin->cur, lang, str, addr);
}
r_name_filter (str, 0);
fi = r_flag_set (r->flags, str, addr, bin_reloc_size (reloc));
if (demname) {
char *realname;
if (r->bin->prefix) {
realname = sdb_fmt ("%s.reloc.%s", r->bin->prefix, demname);
} else {
realname = sdb_fmt ("reloc.%s", demname);
}
r_flag_item_set_realname (fi, realname);
}
} else {
char *reloc_name = get_reloc_name (reloc, addr);
r_flag_set (r->flags, reloc_name, addr, bin_reloc_size (reloc));
}
}
/* Define new data at relocation address if it's not in an executable section */
static void add_metadata(RCore *r, RBinReloc *reloc, ut64 addr, int mode) {
RBinFile * binfile = r->bin->cur;
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
RIOSection *section;
int cdsz;
cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (cdsz == 0) {
return;
}
section = r_io_section_vget (r->io, addr);
if (!section || section->flags & R_IO_EXEC) {
return;
}
if (IS_MODE_SET(mode)) {
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr + cdsz, NULL);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f Cd %d @ 0x%08" PFMT64x "\n", cdsz, addr);
}
}
static bool is_section_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
if (!s || *s->name) {
return false;
}
return (s->type && !strcmp (s->type, "SECTION"));
}
static bool is_section_reloc(RBinReloc *r) {
return is_section_symbol (r->symbol);
}
static bool is_file_symbol(RBinSymbol *s) {
/* workaround for some bin plugs (e.g. ELF) */
return (s && s->type && !strcmp (s->type, "FILE"));
}
static bool is_file_reloc(RBinReloc *r) {
return is_file_symbol (r->symbol);
}
static int bin_relocs(RCore *r, int mode, int va) {
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
RList *relocs;
RListIter *iter;
RBinReloc *reloc = NULL;
Sdb *db = NULL;
char *sdb_module = NULL;
int i = 0;
va = VA_TRUE; // XXX relocs always vaddr?
//this has been created for reloc object files
relocs = r_bin_patch_relocs (r->bin);
if (!relocs) {
relocs = r_bin_get_relocs (r->bin);
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs relocs");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Relocations]");
} else if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "relocs");
}
r_list_foreach (relocs, iter, reloc) {
ut64 addr = rva (r->bin, reloc->paddr, reloc->vaddr, va);
if (IS_MODE_SET (mode) && (is_section_reloc (reloc) || is_file_reloc (reloc))) {
/*
* Skip section reloc because they will have their own flag.
* Skip also file reloc because not useful for now.
*/
} else if (IS_MODE_SET (mode)) {
set_bin_relocs (r, reloc, addr, &db, &sdb_module);
add_metadata (r, reloc, addr, mode);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" %s\n", addr, reloc->import ? reloc->import->name : "");
} else if (IS_MODE_RAD (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: (reloc->symbol ? strdup (reloc->symbol->name) : NULL);
if (name && bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr);
if (mn) {
free (name);
name = mn;
}
}
if (name) {
r_cons_printf ("f %s%s%s @ 0x%08"PFMT64x"\n",
r->bin->prefix ? r->bin->prefix : "reloc.",
r->bin->prefix ? "." : "", name, addr);
add_metadata (r, reloc, addr, mode);
free (name);
}
} else if (IS_MODE_JSON (mode)) {
if (iter->p) {
r_cons_printf (",{\"name\":");
} else {
r_cons_printf ("{\"name\":");
}
// take care with very long symbol names! do not use sdb_fmt or similar
if (reloc->import) {
r_cons_printf ("\"%s\"", reloc->import->name);
} else if (reloc->symbol) {
r_cons_printf ("\"%s\"", reloc->symbol->name);
} else {
r_cons_printf ("null");
}
r_cons_printf (","
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d","
"\"is_ifunc\":%s}",
bin_reloc_type_name (reloc),
reloc->vaddr, reloc->paddr,
r_str_bool (reloc->is_ifunc));
} else if (IS_MODE_NORMAL (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: reloc->symbol
? strdup (reloc->symbol->name)
: strdup ("null");
if (bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr);
if (mn && *mn) {
free (name);
name = mn;
}
}
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" type=%s",
addr, reloc->paddr, bin_reloc_type_name (reloc));
if (reloc->import && reloc->import->name[0]) {
r_cons_printf (" %s", name);
} else if (reloc->symbol && name && name[0]) {
r_cons_printf (" %s", name);
}
free (name);
if (reloc->addend) {
if (reloc->import && reloc->addend > 0) {
r_cons_printf (" +");
}
if (reloc->addend < 0) {
r_cons_printf (" - 0x%08"PFMT64x, -reloc->addend);
} else {
r_cons_printf (" 0x%08"PFMT64x, reloc->addend);
}
}
if (reloc->is_ifunc) {
r_cons_print (" (ifunc)");
}
r_cons_newline ();
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i relocations\n", i);
}
R_FREE (sdb_module);
sdb_free (db);
db = NULL;
return relocs != NULL;
}
#define MYDB 1
/* this is a hacky workaround that needs proper refactoring in Rbin to use Sdb */
#if MYDB
static Sdb *mydb = NULL;
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol, *res = NULL;
RListIter *iter;
if (mydb && symbols && symbols != osymbols) {
sdb_free (mydb);
mydb = NULL;
osymbols = symbols;
}
if (mydb) {
if (name) {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("%x", sdb_hash (name)), NULL);
} else {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt ("0x"PFMT64x, addr), NULL);
}
} else {
mydb = sdb_new0 ();
r_list_foreach (symbols, iter, symbol) {
/* ${name}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("%x", sdb_hash (symbol->name)), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
/* 0x${vaddr}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt ("0x"PFMT64x, symbol->vaddr), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
if (name) {
if (!res && !strcmp (symbol->name, name)) {
res = symbol;
}
} else {
if (symbol->vaddr == addr) {
res = symbol;
}
}
}
osymbols = symbols;
}
return res;
}
#else
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol;
RListIter *iter;
// XXX this is slow, we should use a hashtable here
r_list_foreach (symbols, iter, symbol) {
if (name) {
if (!strcmp (symbol->name, name))
return symbol;
} else {
if (symbol->vaddr == addr) {
return symbol;
}
}
}
return NULL;
}
#endif
/* XXX: This is a hack to get PLT references in rabin2 -i */
/* imp. is a prefix that can be rewritten by the symbol table */
static ut64 impaddr(RBin *bin, int va, const char *name) {
RList *symbols;
if (!name || !*name) {
return false;
}
if (!(symbols = r_bin_get_symbols (bin))) {
return false;
}
char *impname = r_str_newf ("imp.%s", name);
RBinSymbol *s = get_symbol (bin, symbols, impname, 0LL);
// maybe ut64_MAX to indicate import not found?
ut64 addr = s? (va? r_bin_get_vaddr (bin, s->paddr, s->vaddr): s->paddr): 0LL;
free (impname);
return addr;
}
static int bin_imports(RCore *r, int mode, int va, const char *name) {
RBinInfo *info = r_bin_get_info (r->bin);
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
RBinImport *import;
RListIter *iter;
bool lit = info ? info->has_lit: false;
char *str;
int i = 0;
RList *imports = r_bin_get_imports (r->bin);
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs imports");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Imports]");
}
r_list_foreach (imports, iter, import) {
if (name && strcmp (import->name, name)) {
continue;
}
char *symname = strdup (import->name);
ut64 addr = lit ? impaddr (r->bin, va, symname): 0;
if (bin_demangle) {
char *dname = r_bin_demangle (r->bin->cur, NULL, symname, addr);
if (dname) {
free (symname);
symname = r_str_newf ("sym.imp.%s", dname);
free (dname);
}
}
if (r->bin->prefix) {
char *prname = r_str_newf ("%s.%s", r->bin->prefix, symname);
free (symname);
symname = prname;
}
if (IS_MODE_SET (mode)) {
// TODO(eddyb) symbols that are imports.
// Add a dword/qword for PE imports
if (strstr (symname, ".dll_") && cdsz) {
r_meta_add (r->anal, R_META_TYPE_DATA, addr, addr + cdsz, NULL);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_println (symname);
} else if (IS_MODE_JSON (mode)) {
str = r_str_utf16_encode (symname, -1);
str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"type\":\"%s\",",
iter->p ? "," : "",
import->ordinal,
import->bind,
import->type);
if (import->classname && import->classname[0]) {
r_cons_printf ("\"classname\":\"%s\","
"\"descriptor\":\"%s\",",
import->classname,
import->descriptor);
}
r_cons_printf ("\"name\":\"%s\",\"plt\":%"PFMT64d"}",
str, addr);
free (str);
} else if (IS_MODE_RAD (mode)) {
// TODO(eddyb) symbols that are imports.
} else {
const char *bind = r_str_get (import->bind);
const char *type = r_str_get (import->type);
#if 0
r_cons_printf ("ordinal=%03d plt=0x%08"PFMT64x" bind=%s type=%s",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf (" classname=%s", import->classname);
}
r_cons_printf (" name=%s", symname);
if (import->descriptor && import->descriptor[0]) {
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#else
r_cons_printf ("%4d 0x%08"PFMT64x" %7s %7s ",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf ("%s.", import->classname);
}
r_cons_printf ("%s", symname);
if (import->descriptor && import->descriptor[0]) {
// Uh?
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
#endif
}
R_FREE (symname);
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
// r_cons_printf ("# %i imports\n", i);
}
#if MYDB
// NOTE: if we comment out this, it will leak.. but it will be faster
// because it will keep the cache across multiple RBin calls
osymbols = NULL;
sdb_free (mydb);
mydb = NULL;
#endif
return true;
}
static const char *getPrefixFor(const char *s) {
if (s) {
if (!strcmp (s, "NOTYPE")) {
return "loc";
}
if (!strcmp (s, "OBJECT")) {
return "obj";
}
}
return "sym";
}
typedef struct {
const char *pfx; // prefix for flags
char *name; // raw symbol name
char *nameflag; // flag name for symbol
char *demname; // demangled raw symbol name
char *demflag; // flag name for demangled symbol
char *classname; // classname
char *classflag; // flag for classname
char *methname; // methods [class]::[method]
char *methflag; // methods flag sym.[class].[method]
} SymName;
static void snInit(RCore *r, SymName *sn, RBinSymbol *sym, const char *lang) {
#define MAXFLAG_LEN 128
int bin_demangle = lang != NULL;
const char *pfx;
if (!r || !sym || !sym->name) return;
pfx = getPrefixFor (sym->type);
sn->name = strdup (sym->name);
if (sym->dup_count) {
sn->nameflag = r_str_newf ("%s.%s_%d", pfx, sym->name, sym->dup_count);
} else {
sn->nameflag = r_str_newf ("%s.%s", pfx, sym->name);
}
r_name_filter (sn->nameflag, MAXFLAG_LEN);
if (sym->classname && sym->classname[0]) {
sn->classname = strdup (sym->classname);
sn->classflag = r_str_newf ("sym.%s.%s", sn->classname, sn->name);
r_name_filter (sn->classflag, MAXFLAG_LEN);
const char *name = sym->dname? sym->dname: sym->name;
sn->methname = r_str_newf ("%s::%s", sn->classname, name);
sn->methflag = r_str_newf ("sym.%s.%s", sn->classname, name);
r_name_filter (sn->methflag, strlen (sn->methflag));
} else {
sn->classname = NULL;
sn->classflag = NULL;
sn->methname = NULL;
sn->methflag = NULL;
}
sn->demname = NULL;
sn->demflag = NULL;
if (bin_demangle && sym->paddr) {
sn->demname = r_bin_demangle (r->bin->cur, lang, sn->name, sym->vaddr);
if (sn->demname) {
sn->demflag = r_str_newf ("%s.%s", pfx, sn->demname);
r_name_filter (sn->demflag, -1);
}
}
}
static void snFini(SymName *sn) {
R_FREE (sn->name);
R_FREE (sn->nameflag);
R_FREE (sn->demname);
R_FREE (sn->demflag);
R_FREE (sn->classname);
R_FREE (sn->classflag);
R_FREE (sn->methname);
R_FREE (sn->methflag);
}
static bool isAnExport(RBinSymbol *s) {
/* workaround for some bin plugs */
if (!strncmp (s->name, "imp.", 4)) {
return false;
}
return (s->bind && !strcmp (s->bind, "GLOBAL"));
}
static int bin_symbols_internal(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
RList *symbols;
const char *lang;
bool firstexp = true;
bool printHere = false;
int i = 0, is_arm, lastfs = 's';
bool bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
if (args && *args == '.') {
printHere = true;
}
is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
symbols = r_bin_get_symbols (r->bin);
r_space_set (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf (printHere ? "" : "[Symbols]\n");
}
}
r_list_foreach (symbols, iter, symbol) {
ut64 addr = rva (r->bin, symbol->paddr, symbol->vaddr, va);
int len = symbol->size ? symbol->size : 32;
SymName sn;
if (exponly && !isAnExport (symbol)) {
continue;
}
if (name && strcmp (symbol->name, name)) {
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
continue;
}
if ((printHere && !is_in_range (r->offset, symbol->paddr, len))
&& (printHere && !is_in_range (r->offset, addr, len))) {
continue;
}
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) {
/*
* Skip section symbols because they will have their own flag.
* Skip also file symbols because not useful for now.
*/
} else if (IS_MODE_SET (mode)) {
if (is_arm && info->bits < 33) { // 16 or 32
int force_bits = 0;
if (symbol->paddr & 1 || symbol->bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && symbol->bits == 32) {
force_bits = 32;
} else if (!(symbol->paddr & 1) && symbol->bits == 32) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (r->anal, addr, force_bits);
}
}
if (!strncmp (symbol->name, "imp.", 4)) {
if (lastfs != 'i') {
r_flag_space_set (r->flags, "imports");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
r_flag_space_set (r->flags, "symbols");
}
lastfs = 's';
}
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = NULL;
char *comment = NULL;
fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname;
prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
comment = fi->comment ? strdup (fi->comment) : NULL;
r_flag_unset (r->flags, fi);
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *fn, *n;
RFlagItem *fi;
n = sn.demname ? sn.demname : sn.name;
fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_utf16_encode (symbol->name, -1);
// str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""),
str,
sn.demname? sn.demname: "",
sn.nameflag,
symbol->ordinal,
symbol->bind,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: symbol->name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: symbol->name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
RBinFile *binfile;
RBinPlugin *plugin;
char *name = strdup (sn.demname? sn.demname: symbol->name);
r_name_filter (name, -1);
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i')
r_cons_printf ("fs imports\n");
lastfs = 'i';
} else {
if (lastfs != 's') {
r_cons_printf ("fs %s\n",
exponly? "exports": "symbols");
}
lastfs = 's';
}
if (r->bin->prefix) {
if (symbol->dup_count) {
r_cons_printf ("f %s.sym.%s_%d %u 0x%08"PFMT64x"\n",
r->bin->prefix, name, symbol->dup_count, symbol->size, addr);
} else {
r_cons_printf ("f %s.sym.%s %u 0x%08"PFMT64x"\n",
r->bin->prefix, name, symbol->size, addr);
}
} else {
if (symbol->dup_count) {
r_cons_printf ("f sym.%s_%d %u 0x%08"PFMT64x"\n",
name, symbol->dup_count, symbol->size, addr);
} else {
r_cons_printf ("f sym.%s %u 0x%08"PFMT64x"\n",
name, symbol->size, addr);
}
}
binfile = r_core_bin_cur (r);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (!strncmp (plugin->name, "pe", 2)) {
char *p, *module = strdup (symbol->name);
p = strstr (module, ".dll_");
if (p) {
const char *symname = p + 5;
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("k bin/pe/%s/%d=%s.%s\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("k bin/pe/%s/%d=%s\n",
module, symbol->ordinal, symname);
}
}
free (module);
}
}
} else {
const char *bind = r_str_get (symbol->bind);
const char *type = r_str_get (symbol->type);
const char *name = r_str_get (sn.demname? sn.demname: symbol->name);
// const char *fwd = r_str_get (symbol->forwarder);
r_cons_printf ("%03u 0x%08"PFMT64x" 0x%08"PFMT64x" "
"%6s %6s %4d %s\n",
symbol->ordinal,
symbol->paddr, addr, bind, type,
symbol->size, name);
// r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" ord=%03u "
// "fwd=%s sz=%u bind=%s type=%s name=%s\n",
// addr, symbol->paddr, symbol->ordinal, fwd,
// symbol->size, bind, type, name);
}
snFini (&sn);
i++;
if (exponly && firstexp) {
firstexp = false;
}
if (printHere) {
break;
}
}
//handle thumb and arm for entry point since they are not present in symbols
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
if (info->bits < 33) { // 16 or 32
int force_bits = 0;
ut64 addr = rva (r->bin, entry->paddr, entry->vaddr, va);
if (entry->paddr & 1 || entry->bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && entry->bits == 32) {
force_bits = 32;
} else if (!(entry->paddr & 1)) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (r->anal, addr, force_bits);
}
}
}
}
}
if (IS_MODE_JSON (mode) && !printHere) r_cons_printf ("]");
#if 0
if (IS_MODE_NORMAL (mode) && !at) {
r_cons_printf ("\n%i %s\n", i, exponly ? "exports" : "symbols");
}
#endif
r_space_set (&r->anal->meta_spaces, NULL);
return true;
}
static int bin_exports(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *args) {
return bin_symbols_internal (r, mode, laddr, va, at, name, true, args);
}
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *args) {
return bin_symbols_internal (r, mode, laddr, va, at, name, false, args);
}
static char *build_hash_string(int mode, const char *chksum, ut8 *data, ut32 datalen) {
char *chkstr = NULL, *aux, *ret = NULL;
const char *ptr = chksum;
char tmp[128];
int i;
do {
for (i = 0; *ptr && *ptr != ',' && i < sizeof (tmp) -1; i++) {
tmp[i] = *ptr++;
}
tmp[i] = '\0';
r_str_trim_head_tail (tmp);
chkstr = r_hash_to_string (NULL, tmp, data, datalen);
if (!chkstr) {
if (*ptr && *ptr == ',') {
ptr++;
}
continue;
}
if (IS_MODE_SIMPLE (mode)) {
aux = r_str_newf ("%s ", chkstr);
} else if (IS_MODE_JSON (mode)) {
aux = r_str_newf ("\"%s\":\"%s\",", tmp, chkstr);
} else {
aux = r_str_newf ("%s=%s ", tmp, chkstr);
}
ret = r_str_append (ret, aux);
free (chkstr);
free (aux);
if (*ptr && *ptr == ',') ptr++;
} while (*ptr);
return ret;
}
static int bin_sections(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *chksum) {
char *str = NULL;
RBinSection *section;
RBinInfo *info = NULL;
RList *sections;
RListIter *iter;
int i = 0;
int fd = -1;
bool printHere = false;
sections = r_bin_get_sections (r->bin);
bool inDebugger = r_config_get_i (r->config, "cfg.debug");
SdbHash *dup_chk_ht = ht_new (NULL, NULL, NULL);
bool ret = false;
if (!dup_chk_ht) {
return false;
}
if (chksum && *chksum == '.') {
printHere = true;
}
if (IS_MODE_JSON (mode) && !printHere) r_cons_printf ("[");
else if (IS_MODE_RAD (mode) && !at) r_cons_printf ("fs sections\n");
else if (IS_MODE_NORMAL (mode) && !at && !printHere) r_cons_printf ("[Sections]\n");
else if (IS_MODE_NORMAL (mode) && printHere) r_cons_printf("Current section\n");
else if (IS_MODE_SET (mode)) {
fd = r_core_file_cur_fd (r);
r_flag_space_set (r->flags, "sections");
}
r_list_foreach (sections, iter, section) {
char perms[] = "----";
int va_sect = va;
ut64 addr;
if (va && !(section->srwx & R_BIN_SCN_READABLE)) {
va_sect = VA_NOREBASE;
}
addr = rva (r->bin, section->paddr, section->vaddr, va_sect);
if (name && strcmp (section->name, name)) {
continue;
}
if ((printHere && !(section->paddr <= r->offset && r->offset < (section->paddr + section->size)))
&& (printHere && !(addr <= r->offset && r->offset < (addr + section->size)))) {
continue;
}
r_name_filter (section->name, sizeof (section->name));
if (at && (!section->size || !is_in_range (at, addr, section->size))) {
continue;
}
if (section->srwx & R_BIN_SCN_SHAREABLE) perms[0] = 's';
if (section->srwx & R_BIN_SCN_READABLE) perms[1] = 'r';
if (section->srwx & R_BIN_SCN_WRITABLE) perms[2] = 'w';
if (section->srwx & R_BIN_SCN_EXECUTABLE) perms[3] = 'x';
if (IS_MODE_SET (mode)) {
#if LOAD_BSS_MALLOC
if (!strcmp (section->name, ".bss")) {
// check if there's already a file opened there
int loaded = 0;
RListIter *iter;
RIOMap *m;
r_list_foreach (r->io->maps, iter, m) {
if (m->from == addr) {
loaded = 1;
}
}
if (!loaded && !inDebugger) {
r_core_cmdf (r, "on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
}
}
#endif
r_name_filter (section->name, 128);
if (section->format) {
// This is damn slow if section vsize is HUGE
if (section->vsize < 1024 * 1024 * 2) {
r_core_cmdf (r, "%s @ 0x%"PFMT64x, section->format, section->vaddr);
}
}
if (r->bin->prefix) {
str = r_str_newf ("%s.section.%s", r->bin->prefix, section->name);
} else {
str = r_str_newf ("section.%s", section->name);
}
r_flag_set (r->flags, str, addr, section->size);
R_FREE (str);
if (r->bin->prefix) {
str = r_str_newf ("%s.section_end.%s", r->bin->prefix, section->name);
} else {
str = r_str_newf ("section_end.%s", section->name);
}
r_flag_set (r->flags, str, addr + section->vsize, 0);
R_FREE (str);
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (info) {
if (!arch) {
arch = info->arch;
}
if (!bits) {
bits = info->bits;
}
}
//r_io_section_set_archbits (r->io, addr, arch, bits);
}
char *pfx = r->bin->prefix;
str = r_str_newf ("[%02d] %s section size %" PFMT64d" named %s%s%s",
i, perms, section->size,
pfx? pfx: "", pfx? ".": "", section->name);
r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, addr, str);
R_FREE (str);
if (section->add) {
str = r_str_newf ("%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT64x".%"PFMT32u".%s.%"PFMT32u".%d",
section->paddr, addr, section->size, section->vsize, section->srwx, section->name, r->bin->cur->id, fd);
if (!ht_find (dup_chk_ht, str, NULL) && r_io_section_add (r->io, section->paddr, addr,
section->size, section->vsize,
section->srwx, section->name,
r->bin->cur->id, fd)) {
ht_insert (dup_chk_ht, str, NULL);
}
R_FREE (str);
}
} else if (IS_MODE_SIMPLE (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("0x%"PFMT64x" 0x%"PFMT64x" %s %s%s%s\n",
addr, addr + section->size,
perms,
hashstr ? hashstr : "", hashstr ? " " : "",
section->name
);
free (hashstr);
} else if (IS_MODE_JSON (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("%s{\"name\":\"%s\","
"\"size\":%"PFMT64d","
"\"vsize\":%"PFMT64d","
"\"flags\":\"%s\","
"%s"
"\"paddr\":%"PFMT64d","
"\"vaddr\":%"PFMT64d"}",
(iter->p && !printHere)?",":"",
section->name,
section->size,
section->vsize,
perms,
hashstr ? hashstr : "",
section->paddr,
addr);
free (hashstr);
} else if (IS_MODE_RAD (mode)) {
if (!strcmp (section->name, ".bss") && !inDebugger) {
#if LOAD_BSS_MALLOC
r_cons_printf ("on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
#endif
}
if (r->bin->prefix) {
r_cons_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" %s.%s %d\n",
section->paddr, addr, section->size, section->vsize,
r->bin->prefix, section->name, (int)section->srwx);
} else {
r_cons_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" %s %d\n",
section->paddr, addr, section->size, section->vsize,
section->name, (int)section->srwx);
}
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (info) {
if (!arch) arch = info->arch;
if (!bits) bits = info->bits;
}
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
r_cons_printf ("Sa %s %d @ 0x%08"
PFMT64x"\n", arch, bits, addr);
}
if (r->bin->prefix) {
r_cons_printf ("f %s.section.%s %"PFMT64d" 0x%08"PFMT64x"\n",
r->bin->prefix, section->name, section->size, addr);
r_cons_printf ("f %s.section_end.%s 1 0x%08"PFMT64x"\n",
r->bin->prefix, section->name, addr + section->vsize);
r_cons_printf ("CC section %i va=0x%08"PFMT64x" pa=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"rwx=%s %s.%s @ 0x%08"PFMT64x"\n",
i, addr, section->paddr, section->size, section->vsize,
perms, r->bin->prefix, section->name, addr);
} else {
r_cons_printf ("f section.%s %"PFMT64d" 0x%08"PFMT64x"\n",
section->name, section->size, addr);
r_cons_printf ("f section_end.%s 1 0x%08"PFMT64x"\n",
section->name, addr + section->vsize);
r_cons_printf ("CC section %i va=0x%08"PFMT64x" pa=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"rwx=%s %s @ 0x%08"PFMT64x"\n",
i, addr, section->paddr, section->size, section->vsize,
perms, section->name, addr);
}
} else {
char *hashstr = NULL, str[128];
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
goto out;
}
ut32 datalen = section->size;
// VA READ IS BROKEN?
r_io_pread_at (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (!arch && info) {
arch = info->arch;
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
}
if (!bits) {
bits = info? info->bits: R_SYS_BITS;
}
snprintf (str, sizeof (str), "arch=%s bits=%d ",
r_str_get2 (arch), bits);
} else {
str[0] = 0;
}
if (r->bin->prefix) {
#if 0
r_cons_printf ("idx=%02i vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"perm=%s %s%sname=%s.%s\n",
i, addr, section->paddr, section->size, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
#endif
// r_cons_printf ("%02i 0x%08"PFMT64x" %10"PFMT64d" 0x%08"PFMT64x" %10"PFMT64d" "
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s% %s.%s\n",
i, section->paddr, section->size, addr, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
} else {
#if 0
r_cons_printf ("idx=%02i vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"perm=%s %s%sname=%s\n",
i, addr, section->paddr, section->size, section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
#endif
// r_cons_printf ("%02i 0x%08"PFMT64x" %10"PFMT64d" 0x%08"PFMT64x" %10"PFMT64d" "
r_cons_printf ("%02i 0x%08"PFMT64x" %5"PFMT64d" 0x%08"PFMT64x" %5"PFMT64d" "
"%s %s%s%s\n",
i, section->paddr, (ut64)section->size, addr, (ut64)section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
}
free (hashstr);
}
i++;
if (printHere) {
break;
}
}
if (r->bin && r->bin->cur && r->io && !r_io_desc_is_dbg (r->io->desc)) {
r_io_section_apply_bin (r->io, r->bin->cur->id, R_IO_SECTION_APPLY_FOR_ANALYSIS);
}
if (IS_MODE_JSON (mode) && !printHere) {
r_cons_println ("]");
} else if (IS_MODE_NORMAL (mode) && !at && !printHere) {
// r_cons_printf ("\n%i sections\n", i);
}
ret = true;
out:
ht_free (dup_chk_ht);
return ret;
}
static int bin_fields(RCore *r, int mode, int va) {
RList *fields;
RListIter *iter;
RBinField *field;
int i = 0;
RBin *bin = r->bin;
RBinFile *binfile = r_core_bin_cur (r);
ut64 size = binfile ? binfile->size : UT64_MAX;
ut64 baddr = r_bin_get_baddr (r->bin);
if (!(fields = r_bin_get_fields (bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs header");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Header fields]");
}
//why this? there is an overlap in bin_sections with ehdr
//because there can't be two sections with the same name
#if 0
else if (IS_MODE_SET (mode)) {
// XXX: Need more flags??
// this will be set even if the binary does not have an ehdr
int fd = r_core_file_cur_fd(r);
r_io_section_add (r->io, 0, baddr, size, size, 7, "ehdr", 0, fd);
}
#endif
r_list_foreach (fields, iter, field) {
ut64 addr = rva (bin, field->paddr, field->vaddr, va);
if (IS_MODE_RAD (mode)) {
r_name_filter (field->name, -1);
r_cons_printf ("f header.%s @ 0x%08"PFMT64x"\n", field->name, addr);
if (field->comment && *field->comment) {
r_cons_printf ("CC %s @ 0x%"PFMT64x"\n", field->comment, addr);
}
if (field->format && *field->format) {
r_cons_printf ("pf.%s %s\n", field->name, field->format);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"name\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d,
iter->p? ",": "",
field->name,
field->vaddr,
field->paddr
);
if (field->comment && *field->comment) {
// TODO: filter comment before json
r_cons_printf (",\"comment\":\"%s\"", field->comment);
}
if (field->format && *field->format) {
// TODO: filter comment before json
r_cons_printf (",\"format\":\"%s\"", field->format);
}
r_cons_printf ("}");
} else if (IS_MODE_NORMAL (mode)) {
const bool haveComment = (field->comment && *field->comment);
r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s%s%s\n",
field->vaddr, field->paddr, field->name,
haveComment? "; ": "",
haveComment? field->comment: "");
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_RAD (mode)) {
/* add program header section */
r_cons_printf ("S 0 0x%"PFMT64x" 0x%"PFMT64x" 0x%"PFMT64x" ehdr rwx\n",
baddr, size, size);
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i fields\n", i);
}
return true;
}
static char* get_rp (const char* rtype) {
char *rp = NULL;
switch(rtype[0]) {
case 'v':
rp = strdup ("void");
break;
case 'c':
rp = strdup ("char");
break;
case 'i':
rp = strdup ("int");
break;
case 's':
rp = strdup ("short");
break;
case 'l':
rp = strdup ("long");
break;
case 'q':
rp = strdup ("long long");
break;
case 'C':
rp = strdup ("unsigned char");
break;
case 'I':
rp = strdup ("unsigned int");
break;
case 'S':
rp = strdup ("unsigned short");
break;
case 'L':
rp = strdup ("unsigned long");
break;
case 'Q':
rp = strdup ("unsigned long long");
break;
case 'f':
rp = strdup ("float");
break;
case 'd':
rp = strdup ("double");
break;
case 'D':
rp = strdup ("long double");
break;
case 'B':
rp = strdup ("bool");
break;
case '#':
rp = strdup ("CLASS");
break;
default:
rp = strdup ("unknown");
break;
}
return rp;
}
static int bin_classes(RCore *r, int mode) {
RListIter *iter, *iter2, *iter3;
RBinSymbol *sym;
RBinClass *c;
RBinField *f;
char *name;
RList *cs = r_bin_get_classes (r->bin);
if (!cs) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
// XXX: support for classes is broken and needs more love
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
if (!r_config_get_i (r->config, "bin.classes")) {
return false;
}
r_flag_space_set (r->flags, "classes");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs classes");
}
r_list_foreach (cs, iter, c) {
if (!c || !c->name || !c->name[0]) {
continue;
}
name = strdup (c->name);
r_name_filter (name, 0);
ut64 at_min = UT64_MAX;
ut64 at_max = 0LL;
r_list_foreach (c->methods, iter2, sym) {
if (sym->vaddr) {
if (sym->vaddr < at_min) {
at_min = sym->vaddr;
}
if (sym->vaddr + sym->size > at_max) {
at_max = sym->vaddr + sym->size;
}
}
}
if (at_min == UT64_MAX) {
at_min = c->addr;
at_max = c->addr; // XXX + size?
}
if (IS_MODE_SET (mode)) {
const char *classname = sdb_fmt ("class.%s", name);
r_flag_set (r->flags, classname, c->addr, 1);
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *method = sdb_fmt ("method%s.%s.%s",
mflags, c->name, sym->name);
R_FREE (mflags);
r_name_filter (method, -1);
r_flag_set (r->flags, method, sym->vaddr, 1);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %s%s%s\n",
c->addr, at_min, at_max, c->name, c->super ? " " : "",
c->super ? c->super : "");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("\"f class.%s = 0x%"PFMT64x"\"\n",
name, at_min);
if (c->super) {
r_cons_printf ("\"f super.%s.%s = %d\"\n",
c->name, c->super, c->index);
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
char *cmd = r_str_newf ("\"f method%s.%s.%s = 0x%"PFMT64x"\"\n", mflags, c->name, sym->name, sym->vaddr);
r_str_replace_char (cmd, '\n', 0);
r_cons_printf ("%s\n", cmd);
R_FREE (mflags);
free (cmd);
}
} else if (IS_MODE_JSON (mode)) {
if (c->super) {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"super\":\"%s\",\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index, c->super);
} else {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%d,\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index);
}
r_list_foreach (c->methods, iter2, sym) {
if (sym->method_flags) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, mflags, sym->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, sym->vaddr);
}
}
r_cons_printf ("], \"fields\":[");
r_list_foreach (c->fields, iter3, f) {
if (f->flags) {
char *mflags = r_core_bin_method_flags_str (f->flags, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, mflags, f->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter3->p? ",": "", f->name, f->vaddr);
}
}
r_cons_printf ("]}");
} else if (IS_MODE_CLASSDUMP (mode)) {
char *rp = NULL;
if (c) {
//TODO -> Print Superclass
r_cons_printf ("@interface %s : \n{\n", c->name);
r_list_foreach (c->fields, iter2, f) {
if (f->name && r_regex_match ("ivar","e", f->name)) {
r_cons_printf (" %s %s\n", f->type, f->name);
}
}
r_cons_printf ("}\n");
r_list_foreach (c->methods, iter3, sym) {
if (sym->rtype && sym->rtype[0] != '@') {
rp = get_rp (sym->rtype);
r_cons_printf ("%s (%s) %s\n", strncmp (sym->type,"METH",4) ? "+": "-", rp, sym->dname? sym->dname: sym->name);
}
}
r_cons_printf ("@end\n");
}
} else {
int m = 0;
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] (sz %"PFMT64d") class %d %s",
c->addr, at_min, at_max, (at_max - at_min), c->index, c->name);
if (c->super) {
r_cons_printf (" super: %s\n", c->super);
} else {
r_cons_newline ();
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym->method_flags, mode);
r_cons_printf ("0x%08"PFMT64x" method %d %s %s\n",
sym->vaddr, m, mflags, sym->dname? sym->dname: sym->name);
R_FREE (mflags);
m++;
}
}
free (name);
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
return true;
}
static int bin_size(RCore *r, int mode) {
ut64 size = r_bin_get_size (r->bin);
if (IS_MODE_SIMPLE (mode) || IS_MODE_JSON (mode)) {
r_cons_printf ("%"PFMT64u"\n", size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f bin_size @ %"PFMT64u"\n", size);
} else if (IS_MODE_SET (mode)) {
r_core_cmdf (r, "f bin_size @ %"PFMT64u"\n", size);
} else {
r_cons_printf ("%"PFMT64u"\n", size);
}
return true;
}
static int bin_libs(RCore *r, int mode) {
RList *libs;
RListIter *iter;
char* lib;
int i = 0;
if (!(libs = r_bin_get_libs (r->bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Linked libraries]");
}
r_list_foreach (libs, iter, lib) {
if (IS_MODE_SET (mode)) {
// Nothing to set.
// TODO: load libraries with iomaps?
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("CCa entry0 %s\n", lib);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s\"%s\"", iter->p ? "," : "", lib);
} else {
// simple and normal print mode
r_cons_println (lib);
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
if (i == 1) {
r_cons_printf ("\n%i library\n", i);
} else {
r_cons_printf ("\n%i libraries\n", i);
}
}
return true;
}
static void bin_mem_print(RList *mems, int perms, int depth, int mode) {
RBinMem *mem;
RListIter *iter;
if (!mems) {
return;
}
r_list_foreach (mems, iter, mem) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"name\":\"%s\",\"size\":%d,\"address\":%d,"
"\"flags\":\"%s\"}", mem->name, mem->size,
mem->addr, r_str_rwx_i (mem->perms & perms));
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", mem->addr);
} else {
r_cons_printf ("0x%08"PFMT64x" +0x%04x %s %*s%-*s\n",
mem->addr, mem->size, r_str_rwx_i (mem->perms & perms),
depth, "", 20-depth, mem->name);
}
if (mem->mirrors) {
if (IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
bin_mem_print (mem->mirrors, mem->perms & perms, depth + 1, mode);
}
if (IS_MODE_JSON(mode)) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
static int bin_mem(RCore *r, int mode) {
RList *mem = NULL;
if (!r) return false;
if (!IS_MODE_JSON(mode)) {
if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
r_cons_println ("[Memory]\n");
}
}
if (!(mem = r_bin_get_mem (r->bin))) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
bin_mem_print (mem, 7, 0, R_CORE_BIN_JSON);
r_cons_println ("]");
return true;
} else if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
bin_mem_print (mem, 7, 0, mode);
}
return true;
}
static void bin_pe_versioninfo(RCore *r, int mode) {
Sdb *sdb = NULL;
int num_version = 0;
int num_stringtable = 0;
int num_string = 0;
const char *format_version = "bin/cur/info/vs_version_info/VS_VERSIONINFO%d";
const char *format_stringtable = "%s/string_file_info/stringtable%d";
const char *format_string = "%s/string%d";
if (!IS_MODE_JSON (mode)) {
r_cons_printf ("=== VS_VERSIONINFO ===\n\n");
}
bool firstit_dowhile = true;
do {
char path_version[256] = R_EMPTY;
snprintf (path_version, sizeof (path_version), format_version, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (!firstit_dowhile && IS_MODE_JSON (mode)) { r_cons_printf (","); }
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"VS_FIXEDFILEINFO\":{");
} else {
r_cons_printf ("# VS_FIXEDFILEINFO\n\n");
}
char path_fixedfileinfo[256] = R_EMPTY;
snprintf (path_fixedfileinfo, sizeof (path_fixedfileinfo), "%s/fixed_file_info", path_version);
if (!(sdb = sdb_ns_path (r->sdb, path_fixedfileinfo, 0))) {
r_cons_printf ("}");
break;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"Signature\":%"PFMT64u",", sdb_num_get (sdb, "Signature", 0));
} else {
r_cons_printf (" Signature: 0x%"PFMT64x"\n", sdb_num_get (sdb, "Signature", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"StrucVersion\":%"PFMT64u",", sdb_num_get (sdb, "StrucVersion", 0));
} else {
r_cons_printf (" StrucVersion: 0x%"PFMT64x"\n", sdb_num_get (sdb, "StrucVersion", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
} else {
r_cons_printf (" FileVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"ProductVersion\":\"%"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\",",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
} else {
r_cons_printf (" ProductVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileFlagsMask\":%"PFMT64u",", sdb_num_get (sdb, "FileFlagsMask", 0));
} else {
r_cons_printf (" FileFlagsMask: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlagsMask", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileFlags\":%"PFMT64u",", sdb_num_get (sdb, "FileFlags", 0));
} else {
r_cons_printf (" FileFlags: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlags", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileOS\":%"PFMT64u",", sdb_num_get (sdb, "FileOS", 0));
} else {
r_cons_printf (" FileOS: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileOS", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileType\":%"PFMT64u",", sdb_num_get (sdb, "FileType", 0));
} else {
r_cons_printf (" FileType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileType", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"FileSubType\":%"PFMT64u, sdb_num_get (sdb, "FileSubType", 0));
} else {
r_cons_printf (" FileSubType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileSubType", 0));
}
#if 0
r_cons_printf (" FileDate: %d.%d.%d.%d\n",
sdb_num_get (sdb, "FileDateMS", 0) >> 16,
sdb_num_get (sdb, "FileDateMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileDateLS", 0) >> 16,
sdb_num_get (sdb, "FileDateLS", 0) & 0xFFFF);
#endif
if (IS_MODE_JSON (mode)) {
r_cons_printf ("},");
} else {
r_cons_newline ();
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"StringTable\":{");
} else {
r_cons_printf ("# StringTable\n\n");
}
for (num_stringtable = 0; sdb; num_stringtable++) {
char path_stringtable[256] = R_EMPTY;
snprintf (path_stringtable, sizeof (path_stringtable), format_stringtable, path_version, num_stringtable);
sdb = sdb_ns_path (r->sdb, path_stringtable, 0);
bool firstit_for = true;
for (num_string = 0; sdb; num_string++) {
char path_string[256] = R_EMPTY;
snprintf (path_string, sizeof (path_string), format_string, path_stringtable, num_string);
sdb = sdb_ns_path (r->sdb, path_string, 0);
if (sdb) {
if (!firstit_for && IS_MODE_JSON (mode)) { r_cons_printf (","); }
int lenkey = 0;
int lenval = 0;
ut8 *key_utf16 = sdb_decode (sdb_const_get (sdb, "key", 0), &lenkey);
ut8 *val_utf16 = sdb_decode (sdb_const_get (sdb, "value", 0), &lenval);
ut8 *key_utf8 = calloc (lenkey * 2, 1);
ut8 *val_utf8 = calloc (lenval * 2, 1);
if (r_str_utf16_to_utf8 (key_utf8, lenkey * 2, key_utf16, lenkey, true) < 0
|| r_str_utf16_to_utf8 (val_utf8, lenval * 2, val_utf16, lenval, true) < 0) {
eprintf ("Warning: Cannot decode utf16 to utf8\n");
} else if (IS_MODE_JSON (mode)) {
char *escaped_key_utf8 = r_str_escape ((char*)key_utf8);
char *escaped_val_utf8 = r_str_escape ((char*)val_utf8);
r_cons_printf ("\"%s\":\"%s\"", escaped_key_utf8, escaped_val_utf8);
free (escaped_key_utf8);
free (escaped_val_utf8);
} else {
r_cons_printf (" %s: %s\n", (char*)key_utf8, (char*)val_utf8);
}
free (key_utf8);
free (val_utf8);
free (key_utf16);
free (val_utf16);
}
firstit_for = false;
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("}}");
}
num_version++;
firstit_dowhile = false;
} while (sdb);
}
static void bin_elf_versioninfo(RCore *r, int mode) {
const char *format = "bin/cur/info/versioninfo/%s%d";
char path[256] = {0};
int num_versym = 0;
int num_verneed = 0;
int num_version = 0;
Sdb *sdb = NULL;
const char *oValue = NULL;
bool firstit_for_versym = true;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"versym\":[");
}
for (;; num_versym++) {
snprintf (path, sizeof (path), format, "versym", num_versym);
if (!(sdb = sdb_ns_path (r->sdb, path, 0))) {
break;
}
ut64 addr = sdb_num_get (sdb, "addr", 0);
ut64 offset = sdb_num_get (sdb, "offset", 0);
ut64 link = sdb_num_get (sdb, "link", 0);
ut64 num_entries = sdb_num_get (sdb, "num_entries", 0);
const char *section_name = sdb_const_get (sdb, "section_name", 0);
const char *link_section_name = sdb_const_get (sdb, "link_section_name", 0);
if (IS_MODE_JSON (mode)) {
if (!firstit_for_versym) { r_cons_printf (","); }
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
section_name, (ut64)addr, (ut64)offset);
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
(ut32)link, link_section_name);
} else {
r_cons_printf ("Version symbols section '%s' contains %"PFMT64u" entries:\n", section_name, num_entries);
r_cons_printf (" Addr: 0x%08"PFMT64x" Offset: 0x%08"PFMT64x" Link: %x (%s)\n",
(ut64)addr, (ut64)offset, (ut32)link, link_section_name);
}
int i;
for (i = 0; i < num_entries; i++) {
char key[32] = R_EMPTY;
snprintf (key, sizeof (key), "entry%d", i);
const char *value = sdb_const_get (sdb, key, 0);
if (value) {
if (oValue && !strcmp (value, oValue)) {
continue;
}
if (IS_MODE_JSON (mode)) {
if (i > 0) { r_cons_printf (","); }
char *escaped_value = r_str_escape (value);
r_cons_printf ("{\"idx\":%"PFMT64u",\"value\":\"%s\"}",
(ut64) i, escaped_value);
free (escaped_value);
} else {
r_cons_printf (" 0x%08"PFMT64x": ", (ut64) i);
r_cons_printf ("%s\n", value);
}
oValue = value;
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]}");
} else {
r_cons_printf ("\n\n");
}
firstit_for_versym = false;
}
if (IS_MODE_JSON (mode)) { r_cons_printf ("],\"verneed\":["); }
bool firstit_dowhile_verneed = true;
do {
char path_version[256] = R_EMPTY;
snprintf (path, sizeof (path), format, "verneed", num_verneed++);
if (!(sdb = sdb_ns_path (r->sdb, path, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_verneed) { r_cons_printf (","); }
r_cons_printf ("{\"section_name\":\"%s\",\"address\":%"PFMT64u",\"offset\":%"PFMT64u",",
sdb_const_get (sdb, "section_name", 0), sdb_num_get (sdb, "addr", 0), sdb_num_get (sdb, "offset", 0));
r_cons_printf ("\"link\":%"PFMT64u",\"link_section_name\":\"%s\",\"entries\":[",
sdb_num_get (sdb, "link", 0), sdb_const_get (sdb, "link_section_name", 0));
} else {
r_cons_printf ("Version need section '%s' contains %d entries:\n",
sdb_const_get (sdb, "section_name", 0), (int)sdb_num_get (sdb, "num_entries", 0));
r_cons_printf (" Addr: 0x%08"PFMT64x, sdb_num_get (sdb, "addr", 0));
r_cons_printf (" Offset: 0x%08"PFMT64x" Link to section: %"PFMT64d" (%s)\n",
sdb_num_get (sdb, "offset", 0), sdb_num_get (sdb, "link", 0),
sdb_const_get (sdb, "link_section_name", 0));
}
bool firstit_for_verneed = true;
for (num_version = 0;; num_version++) {
snprintf (path_version, sizeof (path_version), "%s/version%d", path, num_version);
const char *filename = NULL;
char path_vernaux[256] = R_EMPTY;
int num_vernaux = 0;
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_for_verneed) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64u",\"vn_version\":%d,",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Version: %d",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
}
if ((filename = sdb_const_get (sdb, "file_name", 0))) {
if (IS_MODE_JSON (mode)) {
char *escaped_filename = r_str_escape (filename);
r_cons_printf ("\"file_name\":\"%s\",", escaped_filename);
free (escaped_filename);
} else {
r_cons_printf (" File: %s", filename);
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"cnt\":%d,", (int)sdb_num_get (sdb, "cnt", 0));
} else {
r_cons_printf (" Cnt: %d\n", (int)sdb_num_get (sdb, "cnt", 0));
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("\"vernaux\":[");
}
bool firstit_dowhile_vernaux = true;
do {
snprintf (path_vernaux, sizeof (path_vernaux), "%s/vernaux%d",
path_version, num_vernaux++);
if (!(sdb = sdb_ns_path (r->sdb, path_vernaux, 0))) {
break;
}
if (IS_MODE_JSON (mode)) {
if (!firstit_dowhile_vernaux) { r_cons_printf (","); }
r_cons_printf ("{\"idx\":%"PFMT64x",\"name\":\"%s\",",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf ("\"flags\":\"%s\",\"version\":%d}",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
} else {
r_cons_printf (" 0x%08"PFMT64x": Name: %s",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf (" Flags: %s Version: %d\n",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
}
firstit_dowhile_vernaux = false;
} while (sdb);
if (IS_MODE_JSON (mode)) { r_cons_printf ("]}"); };
firstit_for_verneed = false;
}
if (IS_MODE_JSON (mode)) { r_cons_printf ("]}"); };
firstit_dowhile_verneed = false;
} while (sdb);
if (IS_MODE_JSON (mode)) { r_cons_printf ("]}"); }
}
static void bin_mach0_versioninfo(RCore *r) {
/* TODO */
}
static void bin_pe_resources(RCore *r, int mode) {
Sdb *sdb = NULL;
int index = 0;
const char *pe_path = "bin/cur/info/pe_resource";
if (!(sdb = sdb_ns_path (r->sdb, pe_path, 0))) {
return;
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "resources");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs resources\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
while (true) {
const char *timestrKey = sdb_fmt ("resource.%d.timestr", index);
const char *vaddrKey = sdb_fmt ("resource.%d.vaddr", index);
const char *sizeKey = sdb_fmt ("resource.%d.size", index);
const char *typeKey = sdb_fmt ("resource.%d.type", index);
const char *languageKey = sdb_fmt ("resource.%d.language", index);
const char *nameKey = sdb_fmt ("resource.%d.name", index);
char *timestr = sdb_get (sdb, timestrKey, 0);
if (!timestr) {
break;
}
ut64 vaddr = sdb_num_get (sdb, vaddrKey, 0);
int size = (int)sdb_num_get (sdb, sizeKey, 0);
int name = (int)sdb_num_get (sdb, nameKey, 0);
char *type = sdb_get (sdb, typeKey, 0);
char *lang = sdb_get (sdb, languageKey, 0);
if (IS_MODE_SET (mode)) {
const char *name = sdb_fmt ("resource.%d", index);
r_flag_set (r->flags, name, vaddr, size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f resource.%d %d 0x%08"PFMT32x"\n", index, size, vaddr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf("%s{\"name\":%d,\"index\":%d, \"type\":\"%s\","
"\"vaddr\":%"PFMT64d", \"size\":%d, \"lang\":\"%s\"}",
index? ",": "", name, index, type, vaddr, size, lang);
} else {
char *humanSize = r_num_units (NULL, size);
r_cons_printf ("Resource %d\n", index);
r_cons_printf (" name: %d\n", name);
r_cons_printf (" timestamp: %s\n", timestr);
r_cons_printf (" vaddr: 0x%08"PFMT64x"\n", vaddr);
if (humanSize) {
r_cons_printf (" size: %s\n", humanSize);
}
r_cons_printf (" type: %s\n", type);
r_cons_printf (" language: %s\n", lang);
free (humanSize);
}
R_FREE (timestr);
R_FREE (type);
R_FREE (lang)
index++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs *");
}
}
static void bin_no_resources(RCore *r, int mode) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[]");
}
}
static int bin_resources(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_resources (r, mode);
} else {
bin_no_resources (r, mode);
}
return true;
}
static int bin_versioninfo(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_versioninfo (r, mode);
} else if (!strncmp ("elf", info->rclass, 3)) {
bin_elf_versioninfo (r, mode);
} else if (!strncmp ("mach0", info->rclass, 5)) {
bin_mach0_versioninfo (r);
} else {
r_cons_println ("Unknown format");
return false;
}
return true;
}
static int bin_signature(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->signature) {
const char *signature = plg->signature (cur, IS_MODE_JSON (mode));
r_cons_println (signature);
free ((char*) signature);
return true;
}
return false;
}
R_API void r_core_bin_export_info_rad(RCore *core) {
Sdb *db = NULL;
char *flagname = NULL, *offset = NULL;
RBinFile *bf = r_core_bin_cur (core);
if (!bf) {
return;
}
db = sdb_ns (bf->sdb, "info", 0);;
if (!db) {
return;
}
if (db) {
SdbListIter *iter;
SdbKv *kv;
r_cons_printf ("fs format\n");
// iterate over all keys
SdbList *ls = sdb_foreach_list (db, false);
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
//printf ("?e (%s) (%s)\n", k, v);
if ((flagname = strstr (dup, ".offset"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("f %s @ %s\n", flagname, v);
free (offset);
offset = strdup (v);
}
if ((flagname = strstr (dup, ".cparse"))) {
r_cons_printf ("\"td %s\"\n", v);
}
free (dup);
}
R_FREE (offset);
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
r_cons_printf ("pf.%s %s\n", flagname, v);
}
free (dup);
}
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
int fmtsize = r_print_format_struct_size (v, core->print, 0, 0);
char *offset_key = r_str_newf ("%s.offset", flagname);
const char *off = sdb_const_get (db, offset_key, 0);
free (offset_key);
if (off) {
r_cons_printf ("Cf %d %s @ %s\n", fmtsize, v, off);
}
}
if ((flagname = strstr (dup, ".size"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("fl %s %s\n", flagname, v);
}
}
free (offset);
}
}
static int bin_header(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->header) {
plg->header (cur);
return true;
}
return false;
}
R_API int r_core_bin_info(RCore *core, int action, int mode, int va, RCoreBinFilter *filter, const char *chksum) {
int ret = true;
const char *name = NULL;
ut64 at = 0, loadaddr = r_bin_get_laddr (core->bin);
if (filter && filter->offset) {
at = filter->offset;
}
if (filter && filter->name) {
name = filter->name;
}
// use our internal values for va
va = va ? VA_TRUE : VA_FALSE;
#if 0
if (r_config_get_i (core->config, "anal.strings")) {
r_core_cmd0 (core, "aar");
}
#endif
if ((action & R_CORE_BIN_ACC_STRINGS)) ret &= bin_strings (core, mode, va);
if ((action & R_CORE_BIN_ACC_RAW_STRINGS)) ret &= bin_raw_strings (core, mode, va);
if ((action & R_CORE_BIN_ACC_INFO)) ret &= bin_info (core, mode);
if ((action & R_CORE_BIN_ACC_MAIN)) ret &= bin_main (core, mode, va);
if ((action & R_CORE_BIN_ACC_DWARF)) ret &= bin_dwarf (core, mode);
if ((action & R_CORE_BIN_ACC_PDB)) ret &= bin_pdb (core, mode);
if ((action & R_CORE_BIN_ACC_ENTRIES)) ret &= bin_entry (core, mode, loadaddr, va, false);
if ((action & R_CORE_BIN_ACC_INITFINI)) ret &= bin_entry (core, mode, loadaddr, va, true);
if ((action & R_CORE_BIN_ACC_SECTIONS)) ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum);
if (r_config_get_i (core->config, "bin.relocs")) {
if ((action & R_CORE_BIN_ACC_RELOCS)) ret &= bin_relocs (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_IMPORTS)) ret &= bin_imports (core, mode, va, name); // 6s
if ((action & R_CORE_BIN_ACC_EXPORTS)) ret &= bin_exports (core, mode, loadaddr, va, at, name, chksum);
if ((action & R_CORE_BIN_ACC_SYMBOLS)) ret &= bin_symbols (core, mode, loadaddr, va, at, name, chksum); // 6s
if ((action & R_CORE_BIN_ACC_LIBS)) ret &= bin_libs (core, mode);
if ((action & R_CORE_BIN_ACC_CLASSES)) ret &= bin_classes (core, mode); // 3s
if ((action & R_CORE_BIN_ACC_SIZE)) ret &= bin_size (core, mode);
if ((action & R_CORE_BIN_ACC_MEM)) ret &= bin_mem (core, mode);
if ((action & R_CORE_BIN_ACC_VERSIONINFO)) ret &= bin_versioninfo (core, mode);
if ((action & R_CORE_BIN_ACC_RESOURCES)) ret &= bin_resources (core, mode);
if ((action & R_CORE_BIN_ACC_SIGNATURE)) ret &= bin_signature (core, mode);
if ((action & R_CORE_BIN_ACC_FIELDS)) {
if (IS_MODE_SIMPLE (mode)) {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
/* ignore mode, just for quiet/simple here */
ret &= bin_fields (core, 0, va);
}
} else {
if (IS_MODE_NORMAL (mode)) {
ret &= bin_header (core, mode);
} else {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
ret &= bin_fields (core, mode, va);
}
}
}
}
return ret;
}
R_API int r_core_bin_set_arch_bits(RCore *r, const char *name, const char * arch, ut16 bits) {
int fd = r_io_fd_get_current (r->io);
RIODesc *desc = r_io_desc_get (r->io, fd);
RBinFile *curfile, *binfile = NULL;
if (!name) {
name = (desc) ? desc->name : NULL;
}
if (!name) {
return false;
}
/* Check if the arch name is a valid name */
if (!r_asm_is_valid (r->assembler, arch)) {
return false;
}
/* Find a file with the requested name/arch/bits */
binfile = r_bin_file_find_by_arch_bits (r->bin, arch, bits, name);
if (!binfile) {
return false;
}
if (!r_bin_use_arch (r->bin, arch, bits, name)) {
return false;
}
curfile = r_bin_cur (r->bin);
//set env if the binfile changed or we are dealing with xtr
if (curfile != binfile || binfile->curxtr) {
r_core_bin_set_cur (r, binfile);
return r_core_bin_set_env (r, binfile);
}
return true;
}
R_API int r_core_bin_update_arch_bits(RCore *r) {
RBinFile *binfile = NULL;
const char *name = NULL, *arch = NULL;
ut16 bits = 0;
if (!r) {
return 0;
}
if (r->assembler) {
bits = r->assembler->bits;
if (r->assembler->cur) {
arch = r->assembler->cur->arch;
}
}
binfile = r_core_bin_cur (r);
name = binfile ? binfile->file : NULL;
if (binfile && binfile->curxtr) {
r_anal_hint_clear (r->anal);
}
return r_core_bin_set_arch_bits (r, name, arch, bits);
}
R_API int r_core_bin_raise(RCore *core, ut32 binfile_idx, ut32 binobj_idx) {
RBin *bin = core->bin;
RBinFile *binfile = NULL;
if (binfile_idx == UT32_MAX && binobj_idx == UT32_MAX) {
return false;
}
if (!r_bin_select_by_ids (bin, binfile_idx, binobj_idx)) {
return false;
}
binfile = r_core_bin_cur (core);
if (binfile) {
r_io_use_fd (core->io, binfile->fd);
}
// it should be 0 to use r_io_use_fd in r_core_block_read
core->switch_file_view = 0;
return binfile && r_core_bin_set_env (core, binfile) && r_core_block_read (core);
}
R_API bool r_core_bin_delete(RCore *core, ut32 binfile_idx, ut32 binobj_idx) {
if (binfile_idx == UT32_MAX && binobj_idx == UT32_MAX) {
return false;
}
if (!r_bin_object_delete (core->bin, binfile_idx, binobj_idx)) {
return false;
}
RBinFile *binfile = r_core_bin_cur (core);
if (binfile) {
r_io_use_fd (core->io, binfile->fd);
}
core->switch_file_view = 0;
return binfile && r_core_bin_set_env (core, binfile) && r_core_block_read (core);
}
static int r_core_bin_file_print(RCore *core, RBinFile *binfile, int mode) {
RListIter *iter;
RBinObject *obj;
const char *name = binfile ? binfile->file : NULL;
(void)r_bin_get_info (core->bin); // XXX is this necssary for proper iniitialization
ut32 id = binfile ? binfile->id : 0;
ut32 fd = binfile ? binfile->fd : 0;
ut32 bin_sz = binfile ? binfile->size : 0;
// TODO: handle mode to print in json and r2 commands
if (!binfile) {
return false;
}
switch (mode) {
case '*':
r_list_foreach (binfile->objs, iter, obj) {
r_cons_printf ("oba 0x%08"PFMT64x" %s # %d\n", obj->boffset, name, obj->id);
}
break;
case 'q':
r_list_foreach (binfile->objs, iter, obj) {
r_cons_printf ("%d\n", obj->id);
}
break;
case 'j':
r_cons_printf ("{\"name\":\"%s\",\"fd\":%d,\"id\":%d,\"size\":%d,\"objs\":[",
name, fd, id, bin_sz);
r_list_foreach (binfile->objs, iter, obj) {
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *arch = info ? info->arch : "unknown";
r_cons_printf ("{\"objid\":%d,\"arch\":\"%s\",\"bits\":%d,\"binoffset\":%"
PFMT64d",\"objsize\":%"PFMT64d"}",
obj->id, arch, bits, obj->boffset, obj->obj_size);
if (iter->n) {
r_cons_print (",");
}
}
r_cons_print ("]}");
break;
default:
r_list_foreach (binfile->objs, iter, obj) {
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *arch = info ? info->arch : "unknown";
if (!arch) {
arch = r_config_get (core->config, "asm.arch");
}
r_cons_printf ("%4d %s-%d at:0x%08"PFMT64x" sz:%"PFMT64d" ",
obj->id, arch, bits, obj->boffset, obj->obj_size );
r_cons_printf ("fd:%d %s\n", fd, name);
}
break;
}
return true;
}
R_API int r_core_bin_list(RCore *core, int mode) {
// list all binfiles and there objects and there archs
int count = 0;
RListIter *iter;
RBinFile *binfile = NULL; //, *cur_bf = r_core_bin_cur (core) ;
RBin *bin = core->bin;
const RList *binfiles = bin ? bin->binfiles: NULL;
if (!binfiles) {
return false;
}
if (mode == 'j') {
r_cons_print ("[");
}
r_list_foreach (binfiles, iter, binfile) {
r_core_bin_file_print (core, binfile, mode);
if (iter->n && mode == 'j') {
r_cons_print (",");
}
}
if (mode == 'j') {
r_cons_println ("]");
}
//r_core_file_set_by_file (core, cur_cf);
//r_core_bin_bind (core, cur_bf);
return count;
}
R_API char *r_core_bin_method_flags_str(ut64 flags, int mode) {
char *str;
RStrBuf *buf;
int i, len = 0;
buf = r_strbuf_new ("");
if (IS_MODE_SET (mode) || IS_MODE_RAD (mode)) {
if (!flags) {
goto out;
}
for (i = 0; i != 64; i++) {
ut64 flag = flags & (1UL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (flag_string) {
r_strbuf_appendf (buf, ".%s", flag_string);
}
}
}
} else if (IS_MODE_JSON (mode)) {
if (!flags) {
r_strbuf_append (buf, "[]");
goto out;
}
r_strbuf_append (buf, "[");
for (i = 0; i != 64; i++) {
ut64 flag = flags & (1LL << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (len != 0) {
r_strbuf_append (buf, ",");
}
if (flag_string) {
r_strbuf_appendf (buf, "\"%s\"", flag_string);
} else {
r_strbuf_appendf (buf, "\"0x%08"PFMT64x"\"", flag);
}
len++;
}
}
r_strbuf_append (buf, "]");
} else {
int pad_len = 4; //TODO: move to a config variable
if (!flags) {
goto padding;
}
for (i = 0; i != 64; i++) {
ut64 flag = flags & (1L << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, true);
if (flag_string) {
r_strbuf_append (buf, flag_string);
} else {
r_strbuf_append (buf, "?");
}
len++;
}
}
padding:
for ( ; len < pad_len; len++) {
r_strbuf_append (buf, " ");
}
}
out:
str = strdup (r_strbuf_get (buf));
r_strbuf_free (buf);
return str;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_140_1 |
crossvul-cpp_data_bad_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]];
data[l++] = 0x8b;
data[l++] = 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/bad_459_0 |
crossvul-cpp_data_good_266_0 | /*
* Copyright (c) 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: Frame Relay 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 "ethertype.h"
#include "llc.h"
#include "nlpid.h"
#include "extract.h"
#include "oui.h"
static void frf15_print(netdissect_options *ndo, const u_char *, u_int);
/*
* the frame relay header has a variable length
*
* the EA bit determines if there is another byte
* in the header
*
* minimum header length is 2 bytes
* maximum header length is 4 bytes
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | DLCI (6 bits) | CR | EA |
* +----+----+----+----+----+----+----+----+
* | DLCI (4 bits) |FECN|BECN| DE | EA |
* +----+----+----+----+----+----+----+----+
* | DLCI (7 bits) | EA |
* +----+----+----+----+----+----+----+----+
* | DLCI (6 bits) |SDLC| EA |
* +----+----+----+----+----+----+----+----+
*/
#define FR_EA_BIT 0x01
#define FR_CR_BIT 0x02000000
#define FR_DE_BIT 0x00020000
#define FR_BECN_BIT 0x00040000
#define FR_FECN_BIT 0x00080000
#define FR_SDLC_BIT 0x00000002
static const struct tok fr_header_flag_values[] = {
{ FR_CR_BIT, "C!" },
{ FR_DE_BIT, "DE" },
{ FR_BECN_BIT, "BECN" },
{ FR_FECN_BIT, "FECN" },
{ FR_SDLC_BIT, "sdlcore" },
{ 0, NULL }
};
/* FRF.15 / FRF.16 */
#define MFR_B_BIT 0x80
#define MFR_E_BIT 0x40
#define MFR_C_BIT 0x20
#define MFR_BEC_MASK (MFR_B_BIT | MFR_E_BIT | MFR_C_BIT)
#define MFR_CTRL_FRAME (MFR_B_BIT | MFR_E_BIT | MFR_C_BIT)
#define MFR_FRAG_FRAME (MFR_B_BIT | MFR_E_BIT )
static const struct tok frf_flag_values[] = {
{ MFR_B_BIT, "Begin" },
{ MFR_E_BIT, "End" },
{ MFR_C_BIT, "Control" },
{ 0, NULL }
};
/* Finds out Q.922 address length, DLCI and flags. Returns 1 on success,
* 0 on invalid address, -1 on truncated packet
* save the flags dep. on address length
*/
static int parse_q922_addr(netdissect_options *ndo,
const u_char *p, u_int *dlci,
u_int *addr_len, uint8_t *flags, u_int length)
{
if (!ND_TTEST(p[0]) || length < 1)
return -1;
if ((p[0] & FR_EA_BIT))
return 0;
if (!ND_TTEST(p[1]) || length < 2)
return -1;
*addr_len = 2;
*dlci = ((p[0] & 0xFC) << 2) | ((p[1] & 0xF0) >> 4);
flags[0] = p[0] & 0x02; /* populate the first flag fields */
flags[1] = p[1] & 0x0c;
flags[2] = 0; /* clear the rest of the flags */
flags[3] = 0;
if (p[1] & FR_EA_BIT)
return 1; /* 2-byte Q.922 address */
p += 2;
length -= 2;
if (!ND_TTEST(p[0]) || length < 1)
return -1;
(*addr_len)++; /* 3- or 4-byte Q.922 address */
if ((p[0] & FR_EA_BIT) == 0) {
*dlci = (*dlci << 7) | (p[0] >> 1);
(*addr_len)++; /* 4-byte Q.922 address */
p++;
length--;
}
if (!ND_TTEST(p[0]) || length < 1)
return -1;
if ((p[0] & FR_EA_BIT) == 0)
return 0; /* more than 4 bytes of Q.922 address? */
flags[3] = p[0] & 0x02;
*dlci = (*dlci << 6) | (p[0] >> 2);
return 1;
}
char *
q922_string(netdissect_options *ndo, const u_char *p, u_int length)
{
static u_int dlci, addr_len;
static uint8_t flags[4];
static char buffer[sizeof("DLCI xxxxxxxxxx")];
memset(buffer, 0, sizeof(buffer));
if (parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length) == 1){
snprintf(buffer, sizeof(buffer), "DLCI %u", dlci);
}
return buffer;
}
/* Frame Relay packet structure, with flags and CRC removed
+---------------------------+
| Q.922 Address* |
+-- --+
| |
+---------------------------+
| Control (UI = 0x03) |
+---------------------------+
| Optional Pad (0x00) |
+---------------------------+
| NLPID |
+---------------------------+
| . |
| . |
| . |
| Data |
| . |
| . |
+---------------------------+
* Q.922 addresses, as presently defined, are two octets and
contain a 10-bit DLCI. In some networks Q.922 addresses
may optionally be increased to three or four octets.
*/
static void
fr_hdr_print(netdissect_options *ndo,
int length, u_int addr_len, u_int dlci, uint8_t *flags, uint16_t nlpid)
{
if (ndo->ndo_qflag) {
ND_PRINT((ndo, "Q.922, DLCI %u, length %u: ",
dlci,
length));
} else {
if (nlpid <= 0xff) /* if its smaller than 256 then its a NLPID */
ND_PRINT((ndo, "Q.922, hdr-len %u, DLCI %u, Flags [%s], NLPID %s (0x%02x), length %u: ",
addr_len,
dlci,
bittok2str(fr_header_flag_values, "none", EXTRACT_32BITS(flags)),
tok2str(nlpid_values,"unknown", nlpid),
nlpid,
length));
else /* must be an ethertype */
ND_PRINT((ndo, "Q.922, hdr-len %u, DLCI %u, Flags [%s], cisco-ethertype %s (0x%04x), length %u: ",
addr_len,
dlci,
bittok2str(fr_header_flag_values, "none", EXTRACT_32BITS(flags)),
tok2str(ethertype_values, "unknown", nlpid),
nlpid,
length));
}
}
u_int
fr_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;
ND_TCHECK2(*p, 4); /* minimum frame header length */
if ((length = fr_print(ndo, p, length)) == 0)
return (0);
else
return length;
trunc:
ND_PRINT((ndo, "[|fr]"));
return caplen;
}
u_int
fr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
int ret;
uint16_t extracted_ethertype;
u_int dlci;
u_int addr_len;
uint16_t nlpid;
u_int hdr_len;
uint8_t flags[4];
ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length);
if (ret == -1)
goto trunc;
if (ret == 0) {
ND_PRINT((ndo, "Q.922, invalid address"));
return 0;
}
ND_TCHECK(p[addr_len]);
if (length < addr_len + 1)
goto trunc;
if (p[addr_len] != LLC_UI && dlci != 0) {
/*
* Let's figure out if we have Cisco-style encapsulation,
* with an Ethernet type (Cisco HDLC type?) following the
* address.
*/
if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) {
/* no Ethertype */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
} else {
extracted_ethertype = EXTRACT_16BITS(p+addr_len);
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci,
flags, extracted_ethertype);
if (ethertype_print(ndo, extracted_ethertype,
p+addr_len+ETHERTYPE_LEN,
length-addr_len-ETHERTYPE_LEN,
ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "UI %02x! ", p[addr_len]));
else
return addr_len + 2;
}
}
ND_TCHECK(p[addr_len+1]);
if (length < addr_len + 2)
goto trunc;
if (p[addr_len + 1] == 0) {
/*
* Assume a pad byte after the control (UI) byte.
* A pad byte should only be used with 3-byte Q.922.
*/
if (addr_len != 3)
ND_PRINT((ndo, "Pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */;
} else {
/*
* Not a pad byte.
* A pad byte should be used with 3-byte Q.922.
*/
if (addr_len == 3)
ND_PRINT((ndo, "No pad! "));
hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */;
}
ND_TCHECK(p[hdr_len - 1]);
if (length < hdr_len)
goto trunc;
nlpid = p[hdr_len - 1];
if (ndo->ndo_eflag)
fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid);
p += hdr_len;
length -= hdr_len;
switch (nlpid) {
case NLPID_IP:
ip_print(ndo, p, length);
break;
case NLPID_IP6:
ip6_print(ndo, p, length);
break;
case NLPID_CLNP:
case NLPID_ESIS:
case NLPID_ISIS:
isoclns_print(ndo, p - 1, length + 1); /* OSI printers need the NLPID field */
break;
case NLPID_SNAP:
if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) {
/* ether_type not known, print raw packet */
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, hdr_len,
dlci, flags, nlpid);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p - hdr_len, length + hdr_len);
}
break;
case NLPID_Q933:
q933_print(ndo, p, length);
break;
case NLPID_MFR:
frf15_print(ndo, p, length);
break;
case NLPID_PPP:
ppp_print(ndo, p, length);
break;
default:
if (!ndo->ndo_eflag)
fr_hdr_print(ndo, length + hdr_len, addr_len,
dlci, flags, nlpid);
if (!ndo->ndo_xflag)
ND_DEFAULTPRINT(p, length);
}
return hdr_len;
trunc:
ND_PRINT((ndo, "[|fr]"));
return 0;
}
u_int
mfr_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;
ND_TCHECK2(*p, 2); /* minimum frame header length */
if ((length = mfr_print(ndo, p, length)) == 0)
return (0);
else
return length;
trunc:
ND_PRINT((ndo, "[|mfr]"));
return caplen;
}
#define MFR_CTRL_MSG_ADD_LINK 1
#define MFR_CTRL_MSG_ADD_LINK_ACK 2
#define MFR_CTRL_MSG_ADD_LINK_REJ 3
#define MFR_CTRL_MSG_HELLO 4
#define MFR_CTRL_MSG_HELLO_ACK 5
#define MFR_CTRL_MSG_REMOVE_LINK 6
#define MFR_CTRL_MSG_REMOVE_LINK_ACK 7
static const struct tok mfr_ctrl_msg_values[] = {
{ MFR_CTRL_MSG_ADD_LINK, "Add Link" },
{ MFR_CTRL_MSG_ADD_LINK_ACK, "Add Link ACK" },
{ MFR_CTRL_MSG_ADD_LINK_REJ, "Add Link Reject" },
{ MFR_CTRL_MSG_HELLO, "Hello" },
{ MFR_CTRL_MSG_HELLO_ACK, "Hello ACK" },
{ MFR_CTRL_MSG_REMOVE_LINK, "Remove Link" },
{ MFR_CTRL_MSG_REMOVE_LINK_ACK, "Remove Link ACK" },
{ 0, NULL }
};
#define MFR_CTRL_IE_BUNDLE_ID 1
#define MFR_CTRL_IE_LINK_ID 2
#define MFR_CTRL_IE_MAGIC_NUM 3
#define MFR_CTRL_IE_TIMESTAMP 5
#define MFR_CTRL_IE_VENDOR_EXT 6
#define MFR_CTRL_IE_CAUSE 7
static const struct tok mfr_ctrl_ie_values[] = {
{ MFR_CTRL_IE_BUNDLE_ID, "Bundle ID"},
{ MFR_CTRL_IE_LINK_ID, "Link ID"},
{ MFR_CTRL_IE_MAGIC_NUM, "Magic Number"},
{ MFR_CTRL_IE_TIMESTAMP, "Timestamp"},
{ MFR_CTRL_IE_VENDOR_EXT, "Vendor Extension"},
{ MFR_CTRL_IE_CAUSE, "Cause"},
{ 0, NULL }
};
#define MFR_ID_STRING_MAXLEN 50
struct ie_tlv_header_t {
uint8_t ie_type;
uint8_t ie_len;
};
u_int
mfr_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int tlen,idx,hdr_len = 0;
uint16_t sequence_num;
uint8_t ie_type,ie_len;
const uint8_t *tptr;
/*
* FRF.16 Link Integrity Control Frame
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | B | E | C=1| 0 0 0 0 | EA |
* +----+----+----+----+----+----+----+----+
* | 0 0 0 0 0 0 0 0 |
* +----+----+----+----+----+----+----+----+
* | message type |
* +----+----+----+----+----+----+----+----+
*/
ND_TCHECK2(*p, 4); /* minimum frame header length */
if ((p[0] & MFR_BEC_MASK) == MFR_CTRL_FRAME && p[1] == 0) {
ND_PRINT((ndo, "FRF.16 Control, Flags [%s], %s, length %u",
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK)),
tok2str(mfr_ctrl_msg_values,"Unknown Message (0x%02x)",p[2]),
length));
tptr = p + 3;
tlen = length -3;
hdr_len = 3;
if (!ndo->ndo_vflag)
return hdr_len;
while (tlen>sizeof(struct ie_tlv_header_t)) {
ND_TCHECK2(*tptr, sizeof(struct ie_tlv_header_t));
ie_type=tptr[0];
ie_len=tptr[1];
ND_PRINT((ndo, "\n\tIE %s (%u), length %u: ",
tok2str(mfr_ctrl_ie_values,"Unknown",ie_type),
ie_type,
ie_len));
/* infinite loop check */
if (ie_type == 0 || ie_len <= sizeof(struct ie_tlv_header_t))
return hdr_len;
ND_TCHECK2(*tptr, ie_len);
tptr+=sizeof(struct ie_tlv_header_t);
/* tlv len includes header */
ie_len-=sizeof(struct ie_tlv_header_t);
tlen-=sizeof(struct ie_tlv_header_t);
switch (ie_type) {
case MFR_CTRL_IE_MAGIC_NUM:
/* FRF.16.1 Section 3.4.3 Magic Number Information Element */
if (ie_len != 4) {
ND_PRINT((ndo, "(invalid length)"));
break;
}
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(tptr)));
break;
case MFR_CTRL_IE_BUNDLE_ID: /* same message format */
case MFR_CTRL_IE_LINK_ID:
for (idx = 0; idx < ie_len && idx < MFR_ID_STRING_MAXLEN; idx++) {
if (*(tptr+idx) != 0) /* don't print null termination */
safeputchar(ndo, *(tptr + idx));
else
break;
}
break;
case MFR_CTRL_IE_TIMESTAMP:
if (ie_len == sizeof(struct timeval)) {
ts_print(ndo, (const struct timeval *)tptr);
break;
}
/* fall through and hexdump if no unix timestamp */
/*
* FIXME those are the defined IEs that lack a decoder
* you are welcome to contribute code ;-)
*/
case MFR_CTRL_IE_VENDOR_EXT:
case MFR_CTRL_IE_CAUSE:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", ie_len);
break;
}
/* do we want to see a hexdump of the IE ? */
if (ndo->ndo_vflag > 1 )
print_unknown_data(ndo, tptr, "\n\t ", ie_len);
tlen-=ie_len;
tptr+=ie_len;
}
return hdr_len;
}
/*
* FRF.16 Fragmentation Frame
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* | B | E | C=0|seq. (high 4 bits) | EA |
* +----+----+----+----+----+----+----+----+
* | sequence (low 8 bits) |
* +----+----+----+----+----+----+----+----+
* | DLCI (6 bits) | CR | EA |
* +----+----+----+----+----+----+----+----+
* | DLCI (4 bits) |FECN|BECN| DE | EA |
* +----+----+----+----+----+----+----+----+
*/
sequence_num = (p[0]&0x1e)<<7 | p[1];
/* whole packet or first fragment ? */
if ((p[0] & MFR_BEC_MASK) == MFR_FRAG_FRAME ||
(p[0] & MFR_BEC_MASK) == MFR_B_BIT) {
ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s], ",
sequence_num,
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK))));
hdr_len = 2;
fr_print(ndo, p+hdr_len,length-hdr_len);
return hdr_len;
}
/* must be a middle or the last fragment */
ND_PRINT((ndo, "FRF.16 Frag, seq %u, Flags [%s]",
sequence_num,
bittok2str(frf_flag_values,"none",(p[0] & MFR_BEC_MASK))));
print_unknown_data(ndo, p, "\n\t", length);
return hdr_len;
trunc:
ND_PRINT((ndo, "[|mfr]"));
return length;
}
/* an NLPID of 0xb1 indicates a 2-byte
* FRF.15 header
*
* 7 6 5 4 3 2 1 0
* +----+----+----+----+----+----+----+----+
* ~ Q.922 header ~
* +----+----+----+----+----+----+----+----+
* | NLPID (8 bits) | NLPID=0xb1
* +----+----+----+----+----+----+----+----+
* | B | E | C |seq. (high 4 bits) | R |
* +----+----+----+----+----+----+----+----+
* | sequence (low 8 bits) |
* +----+----+----+----+----+----+----+----+
*/
#define FR_FRF15_FRAGTYPE 0x01
static void
frf15_print(netdissect_options *ndo,
const u_char *p, u_int length)
{
uint16_t sequence_num, flags;
if (length < 2)
goto trunc;
ND_TCHECK2(*p, 2);
flags = p[0]&MFR_BEC_MASK;
sequence_num = (p[0]&0x1e)<<7 | p[1];
ND_PRINT((ndo, "FRF.15, seq 0x%03x, Flags [%s],%s Fragmentation, length %u",
sequence_num,
bittok2str(frf_flag_values,"none",flags),
p[0]&FR_FRF15_FRAGTYPE ? "Interface" : "End-to-End",
length));
/* TODO:
* depending on all permutations of the B, E and C bit
* dig as deep as we can - e.g. on the first (B) fragment
* there is enough payload to print the IP header
* on non (B) fragments it depends if the fragmentation
* model is end-to-end or interface based wether we want to print
* another Q.922 header
*/
return;
trunc:
ND_PRINT((ndo, "[|frf.15]"));
}
/*
* Q.933 decoding portion for framerelay specific.
*/
/* Q.933 packet format
Format of Other Protocols
using Q.933 NLPID
+-------------------------------+
| Q.922 Address |
+---------------+---------------+
|Control 0x03 | NLPID 0x08 |
+---------------+---------------+
| L2 Protocol ID |
| octet 1 | octet 2 |
+-------------------------------+
| L3 Protocol ID |
| octet 2 | octet 2 |
+-------------------------------+
| Protocol Data |
+-------------------------------+
| FCS |
+-------------------------------+
*/
/* L2 (Octet 1)- Call Reference Usually is 0x0 */
/*
* L2 (Octet 2)- Message Types definition 1 byte long.
*/
/* Call Establish */
#define MSG_TYPE_ESC_TO_NATIONAL 0x00
#define MSG_TYPE_ALERT 0x01
#define MSG_TYPE_CALL_PROCEEDING 0x02
#define MSG_TYPE_CONNECT 0x07
#define MSG_TYPE_CONNECT_ACK 0x0F
#define MSG_TYPE_PROGRESS 0x03
#define MSG_TYPE_SETUP 0x05
/* Call Clear */
#define MSG_TYPE_DISCONNECT 0x45
#define MSG_TYPE_RELEASE 0x4D
#define MSG_TYPE_RELEASE_COMPLETE 0x5A
#define MSG_TYPE_RESTART 0x46
#define MSG_TYPE_RESTART_ACK 0x4E
/* Status */
#define MSG_TYPE_STATUS 0x7D
#define MSG_TYPE_STATUS_ENQ 0x75
static const struct tok fr_q933_msg_values[] = {
{ MSG_TYPE_ESC_TO_NATIONAL, "ESC to National" },
{ MSG_TYPE_ALERT, "Alert" },
{ MSG_TYPE_CALL_PROCEEDING, "Call proceeding" },
{ MSG_TYPE_CONNECT, "Connect" },
{ MSG_TYPE_CONNECT_ACK, "Connect ACK" },
{ MSG_TYPE_PROGRESS, "Progress" },
{ MSG_TYPE_SETUP, "Setup" },
{ MSG_TYPE_DISCONNECT, "Disconnect" },
{ MSG_TYPE_RELEASE, "Release" },
{ MSG_TYPE_RELEASE_COMPLETE, "Release Complete" },
{ MSG_TYPE_RESTART, "Restart" },
{ MSG_TYPE_RESTART_ACK, "Restart ACK" },
{ MSG_TYPE_STATUS, "Status Reply" },
{ MSG_TYPE_STATUS_ENQ, "Status Enquiry" },
{ 0, NULL }
};
#define IE_IS_SINGLE_OCTET(iecode) ((iecode) & 0x80)
#define IE_IS_SHIFT(iecode) (((iecode) & 0xF0) == 0x90)
#define IE_SHIFT_IS_NON_LOCKING(iecode) ((iecode) & 0x08)
#define IE_SHIFT_IS_LOCKING(iecode) (!(IE_SHIFT_IS_NON_LOCKING(iecode)))
#define IE_SHIFT_CODESET(iecode) ((iecode) & 0x07)
#define FR_LMI_ANSI_REPORT_TYPE_IE 0x01
#define FR_LMI_ANSI_LINK_VERIFY_IE_91 0x19 /* details? */
#define FR_LMI_ANSI_LINK_VERIFY_IE 0x03
#define FR_LMI_ANSI_PVC_STATUS_IE 0x07
#define FR_LMI_CCITT_REPORT_TYPE_IE 0x51
#define FR_LMI_CCITT_LINK_VERIFY_IE 0x53
#define FR_LMI_CCITT_PVC_STATUS_IE 0x57
static const struct tok fr_q933_ie_values_codeset_0_5[] = {
{ FR_LMI_ANSI_REPORT_TYPE_IE, "ANSI Report Type" },
{ FR_LMI_ANSI_LINK_VERIFY_IE_91, "ANSI Link Verify" },
{ FR_LMI_ANSI_LINK_VERIFY_IE, "ANSI Link Verify" },
{ FR_LMI_ANSI_PVC_STATUS_IE, "ANSI PVC Status" },
{ FR_LMI_CCITT_REPORT_TYPE_IE, "CCITT Report Type" },
{ FR_LMI_CCITT_LINK_VERIFY_IE, "CCITT Link Verify" },
{ FR_LMI_CCITT_PVC_STATUS_IE, "CCITT PVC Status" },
{ 0, NULL }
};
#define FR_LMI_REPORT_TYPE_IE_FULL_STATUS 0
#define FR_LMI_REPORT_TYPE_IE_LINK_VERIFY 1
#define FR_LMI_REPORT_TYPE_IE_ASYNC_PVC 2
static const struct tok fr_lmi_report_type_ie_values[] = {
{ FR_LMI_REPORT_TYPE_IE_FULL_STATUS, "Full Status" },
{ FR_LMI_REPORT_TYPE_IE_LINK_VERIFY, "Link verify" },
{ FR_LMI_REPORT_TYPE_IE_ASYNC_PVC, "Async PVC Status" },
{ 0, NULL }
};
/* array of 16 codesets - currently we only support codepage 0 and 5 */
static const struct tok *fr_q933_ie_codesets[] = {
fr_q933_ie_values_codeset_0_5,
NULL,
NULL,
NULL,
NULL,
fr_q933_ie_values_codeset_0_5,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
static int fr_q933_print_ie_codeset_0_5(netdissect_options *ndo, u_int iecode,
u_int ielength, const u_char *p);
typedef int (*codeset_pr_func_t)(netdissect_options *, u_int iecode,
u_int ielength, const u_char *p);
/* array of 16 codesets - currently we only support codepage 0 and 5 */
static const codeset_pr_func_t fr_q933_print_ie_codeset[] = {
fr_q933_print_ie_codeset_0_5,
NULL,
NULL,
NULL,
NULL,
fr_q933_print_ie_codeset_0_5,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
/*
* ITU-T Q.933.
*
* p points to octet 2, the octet containing the length of the
* call reference value, so p[n] is octet n+2 ("octet X" is as
* used in Q.931/Q.933).
*
* XXX - actually used both for Q.931 and Q.933.
*/
void
q933_print(netdissect_options *ndo,
const u_char *p, u_int length)
{
u_int olen;
u_int call_ref_length, i;
uint8_t call_ref[15]; /* maximum length - length field is 4 bits */
u_int msgtype;
u_int iecode;
u_int ielength;
u_int codeset = 0;
u_int is_ansi = 0;
u_int ie_is_known;
u_int non_locking_shift;
u_int unshift_codeset;
ND_PRINT((ndo, "%s", ndo->ndo_eflag ? "" : "Q.933"));
if (length == 0 || !ND_TTEST(*p)) {
if (!ndo->ndo_eflag)
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "length %u", length));
goto trunc;
}
/*
* Get the length of the call reference value.
*/
olen = length; /* preserve the original length for display */
call_ref_length = (*p) & 0x0f;
p++;
length--;
/*
* Get the call reference value.
*/
for (i = 0; i < call_ref_length; i++) {
if (length == 0 || !ND_TTEST(*p)) {
if (!ndo->ndo_eflag)
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "length %u", olen));
goto trunc;
}
call_ref[i] = *p;
p++;
length--;
}
/*
* Get the message type.
*/
if (length == 0 || !ND_TTEST(*p)) {
if (!ndo->ndo_eflag)
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "length %u", olen));
goto trunc;
}
msgtype = *p;
p++;
length--;
/*
* Peek ahead to see if we start with a shift.
*/
non_locking_shift = 0;
unshift_codeset = codeset;
if (length != 0) {
if (!ND_TTEST(*p)) {
if (!ndo->ndo_eflag)
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "length %u", olen));
goto trunc;
}
iecode = *p;
if (IE_IS_SHIFT(iecode)) {
/*
* It's a shift. Skip over it.
*/
p++;
length--;
/*
* Get the codeset.
*/
codeset = IE_SHIFT_CODESET(iecode);
/*
* If it's a locking shift to codeset 5,
* mark this as ANSI. (XXX - 5 is actually
* for national variants in general, not
* the US variant in particular, but maybe
* this is more American exceptionalism. :-))
*/
if (IE_SHIFT_IS_LOCKING(iecode)) {
/*
* It's a locking shift.
*/
if (codeset == 5) {
/*
* It's a locking shift to
* codeset 5, so this is
* T1.617 Annex D.
*/
is_ansi = 1;
}
} else {
/*
* It's a non-locking shift.
* Remember the current codeset, so we
* can revert to it after the next IE.
*/
non_locking_shift = 1;
unshift_codeset = 0;
}
}
}
/* printing out header part */
if (!ndo->ndo_eflag)
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "%s, codeset %u", is_ansi ? "ANSI" : "CCITT", codeset));
if (call_ref_length != 0) {
ND_TCHECK(p[0]);
if (call_ref_length > 1 || p[0] != 0) {
/*
* Not a dummy call reference.
*/
ND_PRINT((ndo, ", Call Ref: 0x"));
for (i = 0; i < call_ref_length; i++)
ND_PRINT((ndo, "%02x", call_ref[i]));
}
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo, ", %s (0x%02x), length %u",
tok2str(fr_q933_msg_values,
"unknown message", msgtype),
msgtype,
olen));
} else {
ND_PRINT((ndo, ", %s",
tok2str(fr_q933_msg_values,
"unknown message 0x%02x", msgtype)));
}
/* Loop through the rest of the IEs */
while (length != 0) {
/*
* What's the state of any non-locking shifts?
*/
if (non_locking_shift == 1) {
/*
* There's a non-locking shift in effect for
* this IE. Count it, so we reset the codeset
* before the next IE.
*/
non_locking_shift = 2;
} else if (non_locking_shift == 2) {
/*
* Unshift.
*/
codeset = unshift_codeset;
non_locking_shift = 0;
}
/*
* Get the first octet of the IE.
*/
if (!ND_TTEST(*p)) {
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", length %u", olen));
}
goto trunc;
}
iecode = *p;
p++;
length--;
/* Single-octet IE? */
if (IE_IS_SINGLE_OCTET(iecode)) {
/*
* Yes. Is it a shift?
*/
if (IE_IS_SHIFT(iecode)) {
/*
* Yes. Is it locking?
*/
if (IE_SHIFT_IS_LOCKING(iecode)) {
/*
* Yes.
*/
non_locking_shift = 0;
} else {
/*
* No. Remember the current
* codeset, so we can revert
* to it after the next IE.
*/
non_locking_shift = 1;
unshift_codeset = codeset;
}
/*
* Get the codeset.
*/
codeset = IE_SHIFT_CODESET(iecode);
}
} else {
/*
* No. Get the IE length.
*/
if (length == 0 || !ND_TTEST(*p)) {
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", length %u", olen));
}
goto trunc;
}
ielength = *p;
p++;
length--;
/* lets do the full IE parsing only in verbose mode
* however some IEs (DLCI Status, Link Verify)
* are also interesting in non-verbose mode */
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t%s IE (0x%02x), length %u: ",
tok2str(fr_q933_ie_codesets[codeset],
"unknown", iecode),
iecode,
ielength));
}
/* sanity checks */
if (iecode == 0 || ielength == 0) {
return;
}
if (length < ielength || !ND_TTEST2(*p, ielength)) {
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", length %u", olen));
}
goto trunc;
}
ie_is_known = 0;
if (fr_q933_print_ie_codeset[codeset] != NULL) {
ie_is_known = fr_q933_print_ie_codeset[codeset](ndo, iecode, ielength, p);
}
if (ie_is_known) {
/*
* Known IE; do we want to see a hexdump
* of it?
*/
if (ndo->ndo_vflag > 1) {
/* Yes. */
print_unknown_data(ndo, p, "\n\t ", ielength);
}
} else {
/*
* Unknown IE; if we're printing verbosely,
* print its content in hex.
*/
if (ndo->ndo_vflag >= 1) {
print_unknown_data(ndo, p, "\n\t", ielength);
}
}
length -= ielength;
p += ielength;
}
}
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", length %u", olen));
}
return;
trunc:
ND_PRINT((ndo, "[|q.933]"));
}
static int
fr_q933_print_ie_codeset_0_5(netdissect_options *ndo, u_int iecode,
u_int ielength, const u_char *p)
{
u_int dlci;
switch (iecode) {
case FR_LMI_ANSI_REPORT_TYPE_IE: /* fall through */
case FR_LMI_CCITT_REPORT_TYPE_IE:
if (ielength < 1) {
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", "));
}
ND_PRINT((ndo, "Invalid REPORT TYPE IE"));
return 1;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "%s (%u)",
tok2str(fr_lmi_report_type_ie_values,"unknown",p[0]),
p[0]));
}
return 1;
case FR_LMI_ANSI_LINK_VERIFY_IE: /* fall through */
case FR_LMI_CCITT_LINK_VERIFY_IE:
case FR_LMI_ANSI_LINK_VERIFY_IE_91:
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", "));
}
if (ielength < 2) {
ND_PRINT((ndo, "Invalid LINK VERIFY IE"));
return 1;
}
ND_PRINT((ndo, "TX Seq: %3d, RX Seq: %3d", p[0], p[1]));
return 1;
case FR_LMI_ANSI_PVC_STATUS_IE: /* fall through */
case FR_LMI_CCITT_PVC_STATUS_IE:
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", "));
}
/* now parse the DLCI information element. */
if ((ielength < 3) ||
(p[0] & 0x80) ||
((ielength == 3) && !(p[1] & 0x80)) ||
((ielength == 4) && ((p[1] & 0x80) || !(p[2] & 0x80))) ||
((ielength == 5) && ((p[1] & 0x80) || (p[2] & 0x80) ||
!(p[3] & 0x80))) ||
(ielength > 5) ||
!(p[ielength - 1] & 0x80)) {
ND_PRINT((ndo, "Invalid DLCI in PVC STATUS IE"));
return 1;
}
dlci = ((p[0] & 0x3F) << 4) | ((p[1] & 0x78) >> 3);
if (ielength == 4) {
dlci = (dlci << 6) | ((p[2] & 0x7E) >> 1);
}
else if (ielength == 5) {
dlci = (dlci << 13) | (p[2] & 0x7F) | ((p[3] & 0x7E) >> 1);
}
ND_PRINT((ndo, "DLCI %u: status %s%s", dlci,
p[ielength - 1] & 0x8 ? "New, " : "",
p[ielength - 1] & 0x2 ? "Active" : "Inactive"));
return 1;
}
return 0;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_266_0 |
crossvul-cpp_data_bad_5007_1 | /* $Id: minissdpd.c,v 1.50 2015/08/06 14:05:49 nanard Exp $ */
/* vim: tabstop=4 shiftwidth=4 noexpandtab
* MiniUPnP project
* (c) 2007-2016 Thomas Bernard
* website : http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
* This software is subject to the conditions detailed
* in the LICENCE file provided within the distribution */
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <syslog.h>
#include <ctype.h>
#include <time.h>
#include <sys/queue.h>
/* for chmod : */
#include <sys/stat.h>
/* unix sockets */
#include <sys/un.h>
/* for getpwnam() and getgrnam() */
#if 0
#include <pwd.h>
#include <grp.h>
#endif
#include "getifaddr.h"
#include "upnputils.h"
#include "openssdpsocket.h"
#include "daemonize.h"
#include "codelength.h"
#include "ifacewatch.h"
#include "minissdpdtypes.h"
#include "asyncsendto.h"
#define SET_MAX(max, x) if((x) > (max)) (max) = (x)
/* current request management stucture */
struct reqelem {
int socket;
int is_notify; /* has subscribed to notifications */
LIST_ENTRY(reqelem) entries;
unsigned char * output_buffer;
int output_buffer_offset;
int output_buffer_len;
};
/* device data structures */
struct header {
const char * p; /* string pointer */
int l; /* string length */
};
#define HEADER_NT 0
#define HEADER_USN 1
#define HEADER_LOCATION 2
struct device {
struct device * next;
time_t t; /* validity time */
struct header headers[3]; /* NT, USN and LOCATION headers */
char data[];
};
/* Services stored for answering to M-SEARCH */
struct service {
char * st; /* Service type */
char * usn; /* Unique identifier */
char * server; /* Server string */
char * location; /* URL */
LIST_ENTRY(service) entries;
};
LIST_HEAD(servicehead, service) servicelisthead;
#define NTS_SSDP_ALIVE 1
#define NTS_SSDP_BYEBYE 2
#define NTS_SSDP_UPDATE 3
/* request types */
enum request_type {
MINISSDPD_GET_VERSION = 0,
MINISSDPD_SEARCH_TYPE = 1,
MINISSDPD_SEARCH_USN = 2,
MINISSDPD_SEARCH_ALL = 3,
MINISSDPD_SUBMIT = 4,
MINISSDPD_NOTIF = 5
};
/* discovered device list kept in memory */
struct device * devlist = 0;
/* bootid and configid */
unsigned int upnp_bootid = 1;
unsigned int upnp_configid = 1337;
/* LAN interfaces/addresses */
struct lan_addr_list lan_addrs;
/* connected clients */
LIST_HEAD(reqstructhead, reqelem) reqlisthead;
/* functions prototypes */
#define NOTIF_NEW 1
#define NOTIF_UPDATE 2
#define NOTIF_REMOVE 3
static void
sendNotifications(int notif_type, const struct device * dev, const struct service * serv);
/* functions */
/* parselanaddr()
* parse address with mask
* ex: 192.168.1.1/24 or 192.168.1.1/255.255.255.0
*
* Can also use the interface name (ie eth0)
*
* return value :
* 0 : ok
* -1 : error */
static int
parselanaddr(struct lan_addr_s * lan_addr, const char * str)
{
const char * p;
int n;
char tmp[16];
memset(lan_addr, 0, sizeof(struct lan_addr_s));
p = str;
while(*p && *p != '/' && !isspace(*p))
p++;
n = p - str;
if(!isdigit(str[0]) && n < (int)sizeof(lan_addr->ifname)) {
/* not starting with a digit : suppose it is an interface name */
memcpy(lan_addr->ifname, str, n);
lan_addr->ifname[n] = '\0';
if(getifaddr(lan_addr->ifname, lan_addr->str, sizeof(lan_addr->str),
&lan_addr->addr, &lan_addr->mask) < 0)
goto parselan_error;
/*printf("%s => %s\n", lan_addr->ifname, lan_addr->str);*/
} else {
if(n>15)
goto parselan_error;
memcpy(lan_addr->str, str, n);
lan_addr->str[n] = '\0';
if(!inet_aton(lan_addr->str, &lan_addr->addr))
goto parselan_error;
}
if(*p == '/') {
const char * q = ++p;
while(*p && isdigit(*p))
p++;
if(*p=='.') {
/* parse mask in /255.255.255.0 format */
while(*p && (*p=='.' || isdigit(*p)))
p++;
n = p - q;
if(n>15)
goto parselan_error;
memcpy(tmp, q, n);
tmp[n] = '\0';
if(!inet_aton(tmp, &lan_addr->mask))
goto parselan_error;
} else {
/* it is a /24 format */
int nbits = atoi(q);
if(nbits > 32 || nbits < 0)
goto parselan_error;
lan_addr->mask.s_addr = htonl(nbits ? (0xffffffffu << (32 - nbits)) : 0);
}
} else if(lan_addr->mask.s_addr == 0) {
/* by default, networks are /24 */
lan_addr->mask.s_addr = htonl(0xffffff00u);
}
#ifdef ENABLE_IPV6
if(lan_addr->ifname[0] != '\0') {
lan_addr->index = if_nametoindex(lan_addr->ifname);
if(lan_addr->index == 0)
fprintf(stderr, "Cannot get index for network interface %s",
lan_addr->ifname);
} else {
fprintf(stderr,
"Error: please specify LAN network interface by name instead of IPv4 address : %s\n",
str);
return -1;
}
#endif /* ENABLE_IPV6 */
return 0;
parselan_error:
fprintf(stderr, "Error parsing address/mask (or interface name) : %s\n",
str);
return -1;
}
static int
write_buffer(struct reqelem * req)
{
if(req->output_buffer && req->output_buffer_len > 0) {
int n = write(req->socket,
req->output_buffer + req->output_buffer_offset,
req->output_buffer_len);
if(n >= 0) {
req->output_buffer_offset += n;
req->output_buffer_len -= n;
} else if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
return 0;
}
return n;
} else {
return 0;
}
}
static int
add_to_buffer(struct reqelem * req, const unsigned char * data, int len)
{
unsigned char * tmp;
if(req->output_buffer_offset > 0) {
memmove(req->output_buffer, req->output_buffer + req->output_buffer_offset, req->output_buffer_len);
req->output_buffer_offset = 0;
}
tmp = realloc(req->output_buffer, req->output_buffer_len + len);
if(tmp == NULL) {
syslog(LOG_ERR, "%s: failed to allocate %d bytes",
__func__, req->output_buffer_len + len);
return -1;
}
req->output_buffer = tmp;
memcpy(req->output_buffer + req->output_buffer_len, data, len);
req->output_buffer_len += len;
return len;
}
static int
write_or_buffer(struct reqelem * req, const unsigned char * data, int len)
{
if(write_buffer(req) < 0)
return -1;
if(req->output_buffer && req->output_buffer_len > 0) {
return add_to_buffer(req, data, len);
} else {
int n = write(req->socket, data, len);
if(n == len)
return len;
if(n < 0) {
if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
n = add_to_buffer(req, data, len);
if(n < 0) return n;
} else {
return n;
}
} else {
n = add_to_buffer(req, data + n, len - n);
if(n < 0) return n;
}
}
return len;
}
static const char *
nts_to_str(int nts)
{
switch(nts)
{
case NTS_SSDP_ALIVE:
return "ssdp:alive";
case NTS_SSDP_BYEBYE:
return "ssdp:byebye";
case NTS_SSDP_UPDATE:
return "ssdp:update";
}
return "unknown";
}
/* updateDevice() :
* adds or updates the device to the list.
* return value :
* 0 : the device was updated (or nothing done)
* 1 : the device was new */
static int
updateDevice(const struct header * headers, time_t t)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist; */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
/*printf("found! %d\n", (int)(t - p->t));*/
syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
p->t = t;
/* update Location ! */
if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l)
{
struct device * tmp;
tmp = realloc(p, sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l);
if(!tmp) /* allocation error */
{
syslog(LOG_ERR, "updateDevice() : memory allocation error");
free(p);
return 0;
}
p = tmp;
*pp = p;
}
memcpy(p->data + p->headers[0].l + p->headers[1].l,
headers[2].p, headers[2].l);
/* TODO : check p->headers[HEADER_LOCATION].l */
return 0;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_INFO, "new device discovered : %.*s",
headers[HEADER_USN].l, headers[HEADER_USN].p);
/* add */
{
char * pc;
int i;
p = malloc( sizeof(struct device)
+ headers[0].l+headers[1].l+headers[2].l );
if(!p) {
syslog(LOG_ERR, "updateDevice(): cannot allocate memory");
return -1;
}
p->next = devlist;
p->t = t;
pc = p->data;
for(i = 0; i < 3; i++)
{
p->headers[i].p = pc;
p->headers[i].l = headers[i].l;
memcpy(pc, headers[i].p, headers[i].l);
pc += headers[i].l;
}
devlist = p;
sendNotifications(NOTIF_NEW, p, NULL);
}
return 1;
}
/* removeDevice() :
* remove a device from the list
* return value :
* 0 : no device removed
* -1 : device removed */
static int
removeDevice(const struct header * headers)
{
struct device ** pp = &devlist;
struct device * p = *pp; /* = devlist */
while(p)
{
if( p->headers[HEADER_NT].l == headers[HEADER_NT].l
&& (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l))
&& p->headers[HEADER_USN].l == headers[HEADER_USN].l
&& (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) )
{
syslog(LOG_INFO, "remove device : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
sendNotifications(NOTIF_REMOVE, p, NULL);
*pp = p->next;
free(p);
return -1;
}
pp = &p->next;
p = *pp; /* p = p->next; */
}
syslog(LOG_WARNING, "device not found for removing : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p);
return 0;
}
/* sent notifications to client having subscribed */
static void
sendNotifications(int notif_type, const struct device * dev, const struct service * serv)
{
struct reqelem * req;
unsigned int m;
unsigned char rbuf[RESPONSE_BUFFER_SIZE];
unsigned char * rp;
for(req = reqlisthead.lh_first; req; req = req->entries.le_next) {
if(!req->is_notify) continue;
rbuf[0] = '\xff'; /* special code for notifications */
rbuf[1] = (unsigned char)notif_type;
rbuf[2] = 0;
rp = rbuf + 3;
if(dev) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = dev->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, dev->headers[HEADER_LOCATION].p, dev->headers[HEADER_LOCATION].l);
rp += dev->headers[HEADER_LOCATION].l;
m = dev->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, dev->headers[HEADER_NT].p, dev->headers[HEADER_NT].l);
rp += dev->headers[HEADER_NT].l;
m = dev->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, dev->headers[HEADER_USN].p, dev->headers[HEADER_USN].l);
rp += dev->headers[HEADER_USN].l;
rbuf[2]++;
}
if(serv) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;
m = strlen(serv->st);
CODELENGTH(m, rp);
memcpy(rp, serv->st, m);
rp += m;
m = strlen(serv->usn);
CODELENGTH(m, rp);
memcpy(rp, serv->usn, m);
rp += m;
rbuf[2]++;
}
if(rbuf[2] > 0) {
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
/*goto error;*/
}
}
}
}
/* SendSSDPMSEARCHResponse() :
* build and send response to M-SEARCH SSDP packets. */
static void
SendSSDPMSEARCHResponse(int s, const struct sockaddr * sockname,
const char * st, const char * usn,
const char * server, const char * location)
{
int l, n;
char buf[512];
socklen_t sockname_len;
/*
* follow guideline from document "UPnP Device Architecture 1.0"
* uppercase is recommended.
* DATE: is recommended
* SERVER: OS/ver UPnP/1.0 miniupnpd/1.0
* - check what to put in the 'Cache-Control' header
*
* have a look at the document "UPnP Device Architecture v1.1 */
l = snprintf(buf, sizeof(buf), "HTTP/1.1 200 OK\r\n"
"CACHE-CONTROL: max-age=120\r\n"
/*"DATE: ...\r\n"*/
"ST: %s\r\n"
"USN: %s\r\n"
"EXT:\r\n"
"SERVER: %s\r\n"
"LOCATION: %s\r\n"
"OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01\r\n" /* UDA v1.1 */
"01-NLS: %u\r\n" /* same as BOOTID. UDA v1.1 */
"BOOTID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"CONFIGID.UPNP.ORG: %u\r\n" /* UDA v1.1 */
"\r\n",
st, usn,
server, location,
upnp_bootid, upnp_bootid, upnp_configid);
#ifdef ENABLE_IPV6
sockname_len = (sockname->sa_family == PF_INET6)
? sizeof(struct sockaddr_in6)
: sizeof(struct sockaddr_in);
#else /* ENABLE_IPV6 */
sockname_len = sizeof(struct sockaddr_in);
#endif /* ENABLE_IPV6 */
n = sendto_or_schedule(s, buf, l, 0, sockname, sockname_len);
if(n < 0) {
syslog(LOG_ERR, "%s: sendto(udp): %m", __func__);
}
}
/* Process M-SEARCH requests */
static void
processMSEARCH(int s, const char * st, int st_len,
const struct sockaddr * addr)
{
struct service * serv;
#ifdef ENABLE_IPV6
char buf[64];
#endif /* ENABLE_IPV6 */
if(!st || st_len==0)
return;
#ifdef ENABLE_IPV6
sockaddr_to_string(addr, buf, sizeof(buf));
syslog(LOG_INFO, "SSDP M-SEARCH from %s ST:%.*s",
buf, st_len, st);
#else /* ENABLE_IPV6 */
syslog(LOG_INFO, "SSDP M-SEARCH from %s:%d ST: %.*s",
inet_ntoa(((const struct sockaddr_in *)addr)->sin_addr),
ntohs(((const struct sockaddr_in *)addr)->sin_port),
st_len, st);
#endif /* ENABLE_IPV6 */
if(st_len==8 && (0==memcmp(st, "ssdp:all", 8))) {
/* send a response for all services */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
} else if(st_len > 5 && (0==memcmp(st, "uuid:", 5))) {
/* find a matching UUID value */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->usn, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
}
} else {
/* find matching services */
/* remove version at the end of the ST string */
if(st[st_len-2]==':' && isdigit(st[st_len-1]))
st_len -= 2;
/* answer for each matching service */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strncmp(serv->st, st, st_len)) {
SendSSDPMSEARCHResponse(s, addr,
serv->st, serv->usn,
serv->server, serv->location);
}
}
}
}
/**
* helper function.
* reject any non ASCII or non printable character.
*/
static int
containsForbiddenChars(const unsigned char * p, int len)
{
while(len > 0) {
if(*p < ' ' || *p >= '\x7f')
return 1;
p++;
len--;
}
return 0;
}
#define METHOD_MSEARCH 1
#define METHOD_NOTIFY 2
/* ParseSSDPPacket() :
* parse a received SSDP Packet and call
* updateDevice() or removeDevice() as needed
* return value :
* -1 : a device was removed
* 0 : no device removed nor added
* 1 : a device was added. */
static int
ParseSSDPPacket(int s, const char * p, ssize_t n,
const struct sockaddr * addr,
const char * searched_device)
{
const char * linestart;
const char * lineend;
const char * nameend;
const char * valuestart;
struct header headers[3];
int i, r = 0;
int methodlen;
int nts = -1;
int method = -1;
unsigned int lifetime = 180; /* 3 minutes by default */
const char * st = NULL;
int st_len = 0;
/* first check from what subnet is the sender */
if(get_lan_for_peer(addr) == NULL) {
char addr_str[64];
sockaddr_to_string(addr, addr_str, sizeof(addr_str));
syslog(LOG_WARNING, "peer %s is not from a LAN",
addr_str);
return 0;
}
/* do the parsing */
memset(headers, 0, sizeof(headers));
for(methodlen = 0;
methodlen < n && (isalpha(p[methodlen]) || p[methodlen]=='-');
methodlen++);
if(methodlen==8 && 0==memcmp(p, "M-SEARCH", 8))
method = METHOD_MSEARCH;
else if(methodlen==6 && 0==memcmp(p, "NOTIFY", 6))
method = METHOD_NOTIFY;
else if(methodlen==4 && 0==memcmp(p, "HTTP", 4)) {
/* answer to a M-SEARCH => process it as a NOTIFY
* with NTS: ssdp:alive */
method = METHOD_NOTIFY;
nts = NTS_SSDP_ALIVE;
}
linestart = p;
while(linestart < p + n - 2) {
/* start parsing the line : detect line end */
lineend = linestart;
while(lineend < p + n && *lineend != '\n' && *lineend != '\r')
lineend++;
/*printf("line: '%.*s'\n", lineend - linestart, linestart);*/
/* detect name end : ':' character */
nameend = linestart;
while(nameend < lineend && *nameend != ':')
nameend++;
/* detect value */
if(nameend < lineend)
valuestart = nameend + 1;
else
valuestart = nameend;
/* trim spaces */
while(valuestart < lineend && isspace(*valuestart))
valuestart++;
/* suppress leading " if needed */
if(valuestart < lineend && *valuestart=='\"')
valuestart++;
if(nameend > linestart && valuestart < lineend) {
int l = nameend - linestart; /* header name length */
int m = lineend - valuestart; /* header value length */
/* suppress tailing spaces */
while(m>0 && isspace(valuestart[m-1]))
m--;
/* suppress tailing ' if needed */
if(m>0 && valuestart[m-1] == '\"')
m--;
i = -1;
/*printf("--%.*s: (%d)%.*s--\n", l, linestart,
m, m, valuestart);*/
if(l==2 && 0==strncasecmp(linestart, "nt", 2))
i = HEADER_NT;
else if(l==3 && 0==strncasecmp(linestart, "usn", 3))
i = HEADER_USN;
else if(l==3 && 0==strncasecmp(linestart, "nts", 3)) {
if(m==10 && 0==strncasecmp(valuestart, "ssdp:alive", 10))
nts = NTS_SSDP_ALIVE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:byebye", 11))
nts = NTS_SSDP_BYEBYE;
else if(m==11 && 0==strncasecmp(valuestart, "ssdp:update", 11))
nts = NTS_SSDP_UPDATE;
}
else if(l==8 && 0==strncasecmp(linestart, "location", 8))
i = HEADER_LOCATION;
else if(l==13 && 0==strncasecmp(linestart, "cache-control", 13)) {
/* parse "name1=value1, name_alone, name2=value2" string */
const char * name = valuestart; /* name */
const char * val; /* value */
int rem = m; /* remaining bytes to process */
while(rem > 0) {
val = name;
while(val < name + rem && *val != '=' && *val != ',')
val++;
if(val >= name + rem)
break;
if(*val == '=') {
while(val < name + rem && (*val == '=' || isspace(*val)))
val++;
if(val >= name + rem)
break;
if(0==strncasecmp(name, "max-age", 7))
lifetime = (unsigned int)strtoul(val, 0, 0);
/* move to the next name=value pair */
while(rem > 0 && *name != ',') {
rem--;
name++;
}
/* skip spaces */
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
} else {
rem -= (val - name);
name = val;
while(rem > 0 && (*name == ',' || isspace(*name))) {
rem--;
name++;
}
}
}
/*syslog(LOG_DEBUG, "**%.*s**%u", m, valuestart, lifetime);*/
} else if(l==2 && 0==strncasecmp(linestart, "st", 2)) {
st = valuestart;
st_len = m;
if(method == METHOD_NOTIFY)
i = HEADER_NT; /* it was a M-SEARCH response */
}
if(i>=0) {
headers[i].p = valuestart;
headers[i].l = m;
}
}
linestart = lineend;
while((*linestart == '\n' || *linestart == '\r') && linestart < p + n)
linestart++;
}
#if 0
printf("NTS=%d\n", nts);
for(i=0; i<3; i++) {
if(headers[i].p)
printf("%d-'%.*s'\n", i, headers[i].l, headers[i].p);
}
#endif
syslog(LOG_DEBUG,"SSDP request: '%.*s' (%d) %s %s=%.*s",
methodlen, p, method, nts_to_str(nts),
(method==METHOD_NOTIFY)?"nt":"st",
(method==METHOD_NOTIFY)?headers[HEADER_NT].l:st_len,
(method==METHOD_NOTIFY)?headers[HEADER_NT].p:st);
switch(method) {
case METHOD_NOTIFY:
if(nts==NTS_SSDP_ALIVE || nts==NTS_SSDP_UPDATE) {
if(headers[HEADER_NT].p && headers[HEADER_USN].p && headers[HEADER_LOCATION].p) {
/* filter if needed */
if(searched_device &&
0 != memcmp(headers[HEADER_NT].p, searched_device, headers[HEADER_NT].l))
break;
r = updateDevice(headers, time(NULL) + lifetime);
} else {
syslog(LOG_WARNING, "missing header nt=%p usn=%p location=%p",
headers[HEADER_NT].p, headers[HEADER_USN].p,
headers[HEADER_LOCATION].p);
}
} else if(nts==NTS_SSDP_BYEBYE) {
if(headers[HEADER_NT].p && headers[HEADER_USN].p) {
r = removeDevice(headers);
} else {
syslog(LOG_WARNING, "missing header nt=%p usn=%p",
headers[HEADER_NT].p, headers[HEADER_USN].p);
}
}
break;
case METHOD_MSEARCH:
processMSEARCH(s, st, st_len, addr);
break;
default:
{
char addr_str[64];
sockaddr_to_string(addr, addr_str, sizeof(addr_str));
syslog(LOG_WARNING, "method %.*s, don't know what to do (from %s)",
methodlen, p, addr_str);
}
}
return r;
}
/* OpenUnixSocket()
* open the unix socket and call bind() and listen()
* return -1 in case of error */
static int
OpenUnixSocket(const char * path)
{
struct sockaddr_un addr;
int s;
int rv;
s = socket(AF_UNIX, SOCK_STREAM, 0);
if(s < 0)
{
syslog(LOG_ERR, "socket(AF_UNIX): %m");
return -1;
}
/* unlink the socket pseudo file before binding */
rv = unlink(path);
if(rv < 0 && errno != ENOENT)
{
syslog(LOG_ERR, "unlink(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path));
if(bind(s, (struct sockaddr *)&addr,
sizeof(struct sockaddr_un)) < 0)
{
syslog(LOG_ERR, "bind(unixsocket, \"%s\"): %m", path);
close(s);
return -1;
}
else if(listen(s, 5) < 0)
{
syslog(LOG_ERR, "listen(unixsocket): %m");
close(s);
return -1;
}
/* Change rights so everyone can communicate with us */
if(chmod(path, 0666) < 0)
{
syslog(LOG_WARNING, "chmod(\"%s\"): %m", path);
}
return s;
}
/* processRequest() :
* process the request coming from a unix socket */
void processRequest(struct reqelem * req)
{
ssize_t n;
unsigned int l, m;
unsigned char buf[2048];
const unsigned char * p;
enum request_type type;
struct device * d = devlist;
unsigned char rbuf[RESPONSE_BUFFER_SIZE];
unsigned char * rp;
unsigned char nrep = 0;
time_t t;
struct service * newserv = NULL;
struct service * serv;
n = read(req->socket, buf, sizeof(buf));
if(n<0) {
if(errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
return; /* try again later */
syslog(LOG_ERR, "(s=%d) processRequest(): read(): %m", req->socket);
goto error;
}
if(n==0) {
syslog(LOG_INFO, "(s=%d) request connection closed", req->socket);
goto error;
}
t = time(NULL);
type = buf[0];
p = buf + 1;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding l=%u n=%u)",
l, (unsigned)n);
goto error;
}
if(l == 0 && type != MINISSDPD_SEARCH_ALL
&& type != MINISSDPD_GET_VERSION && type != MINISSDPD_NOTIF) {
syslog(LOG_WARNING, "bad request (length=0, type=%d)", type);
goto error;
}
syslog(LOG_INFO, "(s=%d) request type=%d str='%.*s'",
req->socket, type, l, p);
switch(type) {
case MINISSDPD_GET_VERSION:
rp = rbuf;
CODELENGTH((sizeof(MINISSDPD_VERSION) - 1), rp);
memcpy(rp, MINISSDPD_VERSION, sizeof(MINISSDPD_VERSION) - 1);
rp += (sizeof(MINISSDPD_VERSION) - 1);
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
break;
case MINISSDPD_SEARCH_TYPE: /* request by type */
case MINISSDPD_SEARCH_USN: /* request by USN (unique id) */
case MINISSDPD_SEARCH_ALL: /* everything */
rp = rbuf+1;
while(d && (nrep < 255)) {
if(d->t < t) {
syslog(LOG_INFO, "outdated device");
} else {
/* test if we can put more responses in the buffer */
if(d->headers[HEADER_LOCATION].l + d->headers[HEADER_NT].l
+ d->headers[HEADER_USN].l + 6
+ (rp - rbuf) >= (int)sizeof(rbuf))
break;
if( (type==MINISSDPD_SEARCH_TYPE && 0==memcmp(d->headers[HEADER_NT].p, p, l))
||(type==MINISSDPD_SEARCH_USN && 0==memcmp(d->headers[HEADER_USN].p, p, l))
||(type==MINISSDPD_SEARCH_ALL) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = d->headers[HEADER_LOCATION].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_LOCATION].p, d->headers[HEADER_LOCATION].l);
rp += d->headers[HEADER_LOCATION].l;
m = d->headers[HEADER_NT].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_NT].p, d->headers[HEADER_NT].l);
rp += d->headers[HEADER_NT].l;
m = d->headers[HEADER_USN].l;
CODELENGTH(m, rp);
memcpy(rp, d->headers[HEADER_USN].p, d->headers[HEADER_USN].l);
rp += d->headers[HEADER_USN].l;
nrep++;
}
}
d = d->next;
}
/* Also look in service list */
for(serv = servicelisthead.lh_first;
serv && (nrep < 255);
serv = serv->entries.le_next) {
/* test if we can put more responses in the buffer */
if(strlen(serv->location) + strlen(serv->st)
+ strlen(serv->usn) + 6 + (rp - rbuf) >= sizeof(rbuf))
break;
if( (type==MINISSDPD_SEARCH_TYPE && 0==strncmp(serv->st, (const char *)p, l))
||(type==MINISSDPD_SEARCH_USN && 0==strncmp(serv->usn, (const char *)p, l))
||(type==MINISSDPD_SEARCH_ALL) ) {
/* response :
* 1 - Location
* 2 - NT (device/service type)
* 3 - usn */
m = strlen(serv->location);
CODELENGTH(m, rp);
memcpy(rp, serv->location, m);
rp += m;
m = strlen(serv->st);
CODELENGTH(m, rp);
memcpy(rp, serv->st, m);
rp += m;
m = strlen(serv->usn);
CODELENGTH(m, rp);
memcpy(rp, serv->usn, m);
rp += m;
nrep++;
}
}
rbuf[0] = nrep;
syslog(LOG_DEBUG, "(s=%d) response : %d device%s",
req->socket, nrep, (nrep > 1) ? "s" : "");
if(write_or_buffer(req, rbuf, rp - rbuf) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
break;
case MINISSDPD_SUBMIT: /* submit service */
newserv = malloc(sizeof(struct service));
if(!newserv) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memset(newserv, 0, sizeof(struct service)); /* set pointers to NULL */
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (st contains forbidden chars)");
goto error;
}
newserv->st = malloc(l + 1);
if(!newserv->st) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->st, p, l);
newserv->st[l] = '\0';
p += l;
if(p >= buf + n) {
syslog(LOG_WARNING, "bad request (missing usn)");
goto error;
}
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (usn contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "usn='%.*s'", l, p);
newserv->usn = malloc(l + 1);
if(!newserv->usn) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->usn, p, l);
newserv->usn[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (server contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "server='%.*s'", l, p);
newserv->server = malloc(l + 1);
if(!newserv->server) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->server, p, l);
newserv->server[l] = '\0';
p += l;
DECODELENGTH_CHECKLIMIT(l, p, buf + n);
if(p+l > buf+n) {
syslog(LOG_WARNING, "bad request (length encoding)");
goto error;
}
if(containsForbiddenChars(p, l)) {
syslog(LOG_ERR, "bad request (location contains forbidden chars)");
goto error;
}
syslog(LOG_INFO, "location='%.*s'", l, p);
newserv->location = malloc(l + 1);
if(!newserv->location) {
syslog(LOG_ERR, "cannot allocate memory");
goto error;
}
memcpy(newserv->location, p, l);
newserv->location[l] = '\0';
/* look in service list for duplicate */
for(serv = servicelisthead.lh_first;
serv;
serv = serv->entries.le_next) {
if(0 == strcmp(newserv->usn, serv->usn)
&& 0 == strcmp(newserv->st, serv->st)) {
syslog(LOG_INFO, "Service already in the list. Updating...");
free(newserv->st);
free(newserv->usn);
free(serv->server);
serv->server = newserv->server;
free(serv->location);
serv->location = newserv->location;
free(newserv);
newserv = NULL;
return;
}
}
/* Inserting new service */
LIST_INSERT_HEAD(&servicelisthead, newserv, entries);
sendNotifications(NOTIF_NEW, NULL, newserv);
newserv = NULL;
break;
case MINISSDPD_NOTIF: /* switch socket to notify */
rbuf[0] = '\0';
if(write_or_buffer(req, rbuf, 1) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
req->is_notify = 1;
break;
default:
syslog(LOG_WARNING, "Unknown request type %d", type);
rbuf[0] = '\0';
if(write_or_buffer(req, rbuf, 1) < 0) {
syslog(LOG_ERR, "(s=%d) write: %m", req->socket);
goto error;
}
}
return;
error:
if(newserv) {
free(newserv->st);
free(newserv->usn);
free(newserv->server);
free(newserv->location);
free(newserv);
newserv = NULL;
}
close(req->socket);
req->socket = -1;
return;
}
static volatile sig_atomic_t quitting = 0;
/* SIGTERM signal handler */
static void
sigterm(int sig)
{
(void)sig;
/*int save_errno = errno;*/
/*signal(sig, SIG_IGN);*/
#if 0
/* calling syslog() is forbidden in a signal handler according to
* signal(3) */
syslog(LOG_NOTICE, "received signal %d, good-bye", sig);
#endif
quitting = 1;
/*errno = save_errno;*/
}
#define PORT 1900
#define XSTR(s) STR(s)
#define STR(s) #s
#define UPNP_MCAST_ADDR "239.255.255.250"
/* for IPv6 */
#define UPNP_MCAST_LL_ADDR "FF02::C" /* link-local */
#define UPNP_MCAST_SL_ADDR "FF05::C" /* site-local */
/* send the M-SEARCH request for devices
* either all devices (third argument is NULL or "*") or a specific one */
static void ssdpDiscover(int s, int ipv6, const char * search)
{
static const char MSearchMsgFmt[] =
"M-SEARCH * HTTP/1.1\r\n"
"HOST: %s:" XSTR(PORT) "\r\n"
"ST: %s\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: %u\r\n"
"\r\n";
char bufr[512];
int n;
int mx = 3;
int linklocal = 1;
struct sockaddr_storage sockudp_w;
{
n = snprintf(bufr, sizeof(bufr),
MSearchMsgFmt,
ipv6 ?
(linklocal ? "[" UPNP_MCAST_LL_ADDR "]" : "[" UPNP_MCAST_SL_ADDR "]")
: UPNP_MCAST_ADDR,
(search ? search : "ssdp:all"), mx);
memset(&sockudp_w, 0, sizeof(struct sockaddr_storage));
if(ipv6) {
struct sockaddr_in6 * p = (struct sockaddr_in6 *)&sockudp_w;
p->sin6_family = AF_INET6;
p->sin6_port = htons(PORT);
inet_pton(AF_INET6,
linklocal ? UPNP_MCAST_LL_ADDR : UPNP_MCAST_SL_ADDR,
&(p->sin6_addr));
} else {
struct sockaddr_in * p = (struct sockaddr_in *)&sockudp_w;
p->sin_family = AF_INET;
p->sin_port = htons(PORT);
p->sin_addr.s_addr = inet_addr(UPNP_MCAST_ADDR);
}
n = sendto_or_schedule(s, bufr, n, 0, (const struct sockaddr *)&sockudp_w,
ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
if (n < 0) {
syslog(LOG_ERR, "%s: sendto: %m", __func__);
}
}
}
/* main(): program entry point */
int main(int argc, char * * argv)
{
int ret = 0;
int pid;
struct sigaction sa;
char buf[1500];
ssize_t n;
int s_ssdp = -1; /* udp socket receiving ssdp packets */
#ifdef ENABLE_IPV6
int s_ssdp6 = -1; /* udp socket receiving ssdp packets IPv6*/
#else /* ENABLE_IPV6 */
#define s_ssdp6 (-1)
#endif /* ENABLE_IPV6 */
int s_unix = -1; /* unix socket communicating with clients */
int s_ifacewatch = -1; /* socket to receive Route / network interface config changes */
struct reqelem * req;
struct reqelem * reqnext;
fd_set readfds;
fd_set writefds;
struct timeval now;
int max_fd;
struct lan_addr_s * lan_addr;
int i;
const char * sockpath = "/var/run/minissdpd.sock";
const char * pidfilename = "/var/run/minissdpd.pid";
int debug_flag = 0;
#ifdef ENABLE_IPV6
int ipv6 = 0;
#endif /* ENABLE_IPV6 */
int deltadev = 0;
struct sockaddr_in sendername;
socklen_t sendername_len;
#ifdef ENABLE_IPV6
struct sockaddr_in6 sendername6;
socklen_t sendername6_len;
#endif /* ENABLE_IPV6 */
unsigned char ttl = 2; /* UDA says it should default to 2 */
const char * searched_device = NULL; /* if not NULL, search/filter a specific device type */
LIST_INIT(&reqlisthead);
LIST_INIT(&servicelisthead);
LIST_INIT(&lan_addrs);
/* process command line */
for(i=1; i<argc; i++)
{
if(0==strcmp(argv[i], "-d"))
debug_flag = 1;
#ifdef ENABLE_IPV6
else if(0==strcmp(argv[i], "-6"))
ipv6 = 1;
#endif /* ENABLE_IPV6 */
else {
if((i + 1) >= argc) {
fprintf(stderr, "option %s needs an argument.\n", argv[i]);
break;
}
if(0==strcmp(argv[i], "-i")) {
lan_addr = malloc(sizeof(struct lan_addr_s));
if(lan_addr == NULL) {
fprintf(stderr, "malloc(%d) FAILED\n", (int)sizeof(struct lan_addr_s));
break;
}
if(parselanaddr(lan_addr, argv[++i]) != 0) {
fprintf(stderr, "can't parse \"%s\" as a valid address or interface name\n", argv[i]);
free(lan_addr);
} else {
LIST_INSERT_HEAD(&lan_addrs, lan_addr, list);
}
} else if(0==strcmp(argv[i], "-s"))
sockpath = argv[++i];
else if(0==strcmp(argv[i], "-p"))
pidfilename = argv[++i];
else if(0==strcmp(argv[i], "-t"))
ttl = (unsigned char)atoi(argv[++i]);
else if(0==strcmp(argv[i], "-f"))
searched_device = argv[++i];
else
fprintf(stderr, "unknown commandline option %s.\n", argv[i]);
}
}
if(lan_addrs.lh_first == NULL)
{
fprintf(stderr,
"Usage: %s [-d] "
#ifdef ENABLE_IPV6
"[-6] "
#endif /* ENABLE_IPV6 */
"[-s socket] [-p pidfile] [-t TTL] "
"[-f device] "
"-i <interface> [-i <interface2>] ...\n",
argv[0]);
fprintf(stderr,
"\n <interface> is either an IPv4 address with mask such as\n"
" 192.168.1.42/255.255.255.0, or an interface name such as eth0.\n");
fprintf(stderr,
"\n By default, socket will be open as %s\n"
" and pid written to file %s\n",
sockpath, pidfilename);
return 1;
}
/* open log */
openlog("minissdpd",
LOG_CONS|LOG_PID|(debug_flag?LOG_PERROR:0),
LOG_MINISSDPD);
if(!debug_flag) /* speed things up and ignore LOG_INFO and LOG_DEBUG */
setlogmask(LOG_UPTO(LOG_NOTICE));
if(checkforrunning(pidfilename) < 0)
{
syslog(LOG_ERR, "MiniSSDPd is already running. EXITING");
return 1;
}
upnp_bootid = (unsigned int)time(NULL);
/* set signal handlers */
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sigterm;
if(sigaction(SIGTERM, &sa, NULL))
{
syslog(LOG_ERR, "Failed to set SIGTERM handler. EXITING");
ret = 1;
goto quit;
}
if(sigaction(SIGINT, &sa, NULL))
{
syslog(LOG_ERR, "Failed to set SIGINT handler. EXITING");
ret = 1;
goto quit;
}
/* open route/interface config changes socket */
s_ifacewatch = OpenAndConfInterfaceWatchSocket();
/* open UDP socket(s) for receiving SSDP packets */
s_ssdp = OpenAndConfSSDPReceiveSocket(0, ttl);
if(s_ssdp < 0)
{
syslog(LOG_ERR, "Cannot open socket for receiving SSDP messages, exiting");
ret = 1;
goto quit;
}
#ifdef ENABLE_IPV6
if(ipv6) {
s_ssdp6 = OpenAndConfSSDPReceiveSocket(1, ttl);
if(s_ssdp6 < 0)
{
syslog(LOG_ERR, "Cannot open socket for receiving SSDP messages (IPv6), exiting");
ret = 1;
goto quit;
}
}
#endif /* ENABLE_IPV6 */
/* Open Unix socket to communicate with other programs on
* the same machine */
s_unix = OpenUnixSocket(sockpath);
if(s_unix < 0)
{
syslog(LOG_ERR, "Cannot open unix socket for communicating with clients. Exiting");
ret = 1;
goto quit;
}
/* drop privileges */
#if 0
/* if we drop privileges, how to unlink(/var/run/minissdpd.sock) ? */
if(getuid() == 0) {
struct passwd * user;
struct group * group;
user = getpwnam("nobody");
if(!user) {
syslog(LOG_ERR, "getpwnam(\"%s\") : %m", "nobody");
ret = 1;
goto quit;
}
group = getgrnam("nogroup");
if(!group) {
syslog(LOG_ERR, "getgrnam(\"%s\") : %m", "nogroup");
ret = 1;
goto quit;
}
if(setgid(group->gr_gid) < 0) {
syslog(LOG_ERR, "setgit(%d) : %m", group->gr_gid);
ret = 1;
goto quit;
}
if(setuid(user->pw_uid) < 0) {
syslog(LOG_ERR, "setuid(%d) : %m", user->pw_uid);
ret = 1;
goto quit;
}
}
#endif
/* daemonize or in any case get pid ! */
if(debug_flag)
pid = getpid();
else {
#ifdef USE_DAEMON
if(daemon(0, 0) < 0)
perror("daemon()");
pid = getpid();
#else /* USE_DAEMON */
pid = daemonize();
#endif /* USE_DAEMON */
}
writepidfile(pidfilename, pid);
/* send M-SEARCH ssdp:all Requests */
if(s_ssdp >= 0)
ssdpDiscover(s_ssdp, 0, searched_device);
if(s_ssdp6 >= 0)
ssdpDiscover(s_ssdp6, 1, searched_device);
/* Main loop */
while(!quitting) {
/* fill readfds fd_set */
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_SET(s_unix, &readfds);
max_fd = s_unix;
if(s_ssdp >= 0) {
FD_SET(s_ssdp, &readfds);
SET_MAX(max_fd, s_ssdp);
}
#ifdef ENABLE_IPV6
if(s_ssdp6 >= 0) {
FD_SET(s_ssdp6, &readfds);
SET_MAX(max_fd, s_ssdp6);
}
#endif /* ENABLE_IPV6 */
if(s_ifacewatch >= 0) {
FD_SET(s_ifacewatch, &readfds);
SET_MAX(max_fd, s_ifacewatch);
}
for(req = reqlisthead.lh_first; req; req = req->entries.le_next) {
if(req->socket >= 0) {
FD_SET(req->socket, &readfds);
SET_MAX(max_fd, req->socket);
}
if(req->output_buffer_len > 0) {
FD_SET(req->socket, &writefds);
SET_MAX(max_fd, req->socket);
}
}
gettimeofday(&now, NULL);
i = get_sendto_fds(&writefds, &max_fd, &now);
/* select call */
if(select(max_fd + 1, &readfds, &writefds, 0, 0) < 0) {
if(errno != EINTR) {
syslog(LOG_ERR, "select: %m");
break; /* quit */
}
continue; /* try again */
}
if(try_sendto(&writefds) < 0) {
syslog(LOG_ERR, "try_sendto: %m");
break;
}
#ifdef ENABLE_IPV6
if((s_ssdp6 >= 0) && FD_ISSET(s_ssdp6, &readfds))
{
sendername6_len = sizeof(struct sockaddr_in6);
n = recvfrom(s_ssdp6, buf, sizeof(buf), 0,
(struct sockaddr *)&sendername6, &sendername6_len);
if(n<0)
{
/* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)
* other errors : log to LOG_ERR */
if(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
syslog(LOG_ERR, "recvfrom: %m");
}
else
{
/* Parse and process the packet received */
/*printf("%.*s", n, buf);*/
i = ParseSSDPPacket(s_ssdp6, buf, n,
(struct sockaddr *)&sendername6, searched_device);
syslog(LOG_DEBUG, "** i=%d deltadev=%d **", i, deltadev);
if(i==0 || (i*deltadev < 0))
{
if(deltadev > 0)
syslog(LOG_NOTICE, "%d new devices added", deltadev);
else if(deltadev < 0)
syslog(LOG_NOTICE, "%d devices removed (good-bye!)", -deltadev);
deltadev = i;
}
else if((i*deltadev) >= 0)
{
deltadev += i;
}
}
}
#endif /* ENABLE_IPV6 */
if((s_ssdp >= 0) && FD_ISSET(s_ssdp, &readfds))
{
sendername_len = sizeof(struct sockaddr_in);
n = recvfrom(s_ssdp, buf, sizeof(buf), 0,
(struct sockaddr *)&sendername, &sendername_len);
if(n<0)
{
/* EAGAIN, EWOULDBLOCK, EINTR : silently ignore (try again next time)
* other errors : log to LOG_ERR */
if(errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
syslog(LOG_ERR, "recvfrom: %m");
}
else
{
/* Parse and process the packet received */
/*printf("%.*s", n, buf);*/
i = ParseSSDPPacket(s_ssdp, buf, n,
(struct sockaddr *)&sendername, searched_device);
syslog(LOG_DEBUG, "** i=%d deltadev=%d **", i, deltadev);
if(i==0 || (i*deltadev < 0))
{
if(deltadev > 0)
syslog(LOG_NOTICE, "%d new devices added", deltadev);
else if(deltadev < 0)
syslog(LOG_NOTICE, "%d devices removed (good-bye!)", -deltadev);
deltadev = i;
}
else if((i*deltadev) >= 0)
{
deltadev += i;
}
}
}
/* processing unix socket requests */
for(req = reqlisthead.lh_first; req;) {
reqnext = req->entries.le_next;
if((req->socket >= 0) && FD_ISSET(req->socket, &readfds)) {
processRequest(req);
}
if((req->socket >= 0) && FD_ISSET(req->socket, &writefds)) {
write_buffer(req);
}
if(req->socket < 0) {
LIST_REMOVE(req, entries);
free(req->output_buffer);
free(req);
}
req = reqnext;
}
/* processing new requests */
if(FD_ISSET(s_unix, &readfds))
{
struct reqelem * tmp;
int s = accept(s_unix, NULL, NULL);
if(s < 0) {
syslog(LOG_ERR, "accept(s_unix): %m");
} else {
syslog(LOG_INFO, "(s=%d) new request connection", s);
if(!set_non_blocking(s))
syslog(LOG_WARNING, "Failed to set new socket non blocking : %m");
tmp = malloc(sizeof(struct reqelem));
if(!tmp) {
syslog(LOG_ERR, "cannot allocate memory for request");
close(s);
} else {
memset(tmp, 0, sizeof(struct reqelem));
tmp->socket = s;
LIST_INSERT_HEAD(&reqlisthead, tmp, entries);
}
}
}
/* processing route/network interface config changes */
if((s_ifacewatch >= 0) && FD_ISSET(s_ifacewatch, &readfds)) {
ProcessInterfaceWatch(s_ifacewatch, s_ssdp, s_ssdp6);
}
}
syslog(LOG_DEBUG, "quitting...");
finalize_sendto();
/* closing and cleaning everything */
quit:
if(s_ssdp >= 0) {
close(s_ssdp);
s_ssdp = -1;
}
#ifdef ENABLE_IPV6
if(s_ssdp6 >= 0) {
close(s_ssdp6);
s_ssdp6 = -1;
}
#endif /* ENABLE_IPV6 */
if(s_unix >= 0) {
close(s_unix);
s_unix = -1;
if(unlink(sockpath) < 0)
syslog(LOG_ERR, "unlink(%s): %m", sockpath);
}
if(s_ifacewatch >= 0) {
close(s_ifacewatch);
s_ifacewatch = -1;
}
/* empty LAN interface/address list */
while(lan_addrs.lh_first != NULL) {
lan_addr = lan_addrs.lh_first;
LIST_REMOVE(lan_addrs.lh_first, list);
free(lan_addr);
}
/* empty device list */
while(devlist != NULL) {
struct device * next = devlist->next;
free(devlist);
devlist = next;
}
/* empty service list */
while(servicelisthead.lh_first != NULL) {
struct service * serv = servicelisthead.lh_first;
LIST_REMOVE(servicelisthead.lh_first, entries);
free(serv->st);
free(serv->usn);
free(serv->server);
free(serv->location);
free(serv);
}
if(unlink(pidfilename) < 0)
syslog(LOG_ERR, "unlink(%s): %m", pidfilename);
closelog();
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5007_1 |
crossvul-cpp_data_good_2746_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: Cisco HDLC printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ethertype.h"
#include "extract.h"
#include "chdlc.h"
static void chdlc_slarp_print(netdissect_options *, const u_char *, u_int);
static const struct tok chdlc_cast_values[] = {
{ CHDLC_UNICAST, "unicast" },
{ CHDLC_BCAST, "bcast" },
{ 0, NULL}
};
/* Standard CHDLC printer */
u_int
chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p)
{
return chdlc_print(ndo, p, h->len);
}
u_int
chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length)
{
u_int proto;
const u_char *bp = p;
if (length < CHDLC_HDRLEN)
goto trunc;
ND_TCHECK2(*p, CHDLC_HDRLEN);
proto = EXTRACT_16BITS(&p[2]);
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ",
tok2str(chdlc_cast_values, "0x%02x", p[0]),
tok2str(ethertype_values, "Unknown", proto),
proto,
length));
}
length -= CHDLC_HDRLEN;
p += CHDLC_HDRLEN;
switch (proto) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
break;
case CHDLC_TYPE_SLARP:
chdlc_slarp_print(ndo, p, length);
break;
#if 0
case CHDLC_TYPE_CDP:
chdlc_cdp_print(p, length);
break;
#endif
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
break;
case ETHERTYPE_ISO:
/* is the fudge byte set ? lets verify by spotting ISO headers */
if (length < 2)
goto trunc;
ND_TCHECK_16BITS(p);
if (*(p+1) == 0x81 ||
*(p+1) == 0x82 ||
*(p+1) == 0x83)
isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1);
else
isoclns_print(ndo, p, length, ndo->ndo_snapend - p);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto));
break;
}
return (CHDLC_HDRLEN);
trunc:
ND_PRINT((ndo, "[|chdlc]"));
return ndo->ndo_snapend - bp;
}
/*
* The fixed-length portion of a SLARP packet.
*/
struct cisco_slarp {
uint8_t code[4];
#define SLARP_REQUEST 0
#define SLARP_REPLY 1
#define SLARP_KEEPALIVE 2
union {
struct {
uint8_t addr[4];
uint8_t mask[4];
} addr;
struct {
uint8_t myseq[4];
uint8_t yourseq[4];
uint8_t rel[2];
} keep;
} un;
};
#define SLARP_MIN_LEN 14
#define SLARP_MAX_LEN 18
static void
chdlc_slarp_print(netdissect_options *ndo, const u_char *cp, u_int length)
{
const struct cisco_slarp *slarp;
u_int sec,min,hrs,days;
ND_PRINT((ndo, "SLARP (length: %u), ",length));
if (length < SLARP_MIN_LEN)
goto trunc;
slarp = (const struct cisco_slarp *)cp;
ND_TCHECK2(*slarp, SLARP_MIN_LEN);
switch (EXTRACT_32BITS(&slarp->code)) {
case SLARP_REQUEST:
ND_PRINT((ndo, "request"));
/*
* At least according to William "Chops" Westfield's
* message in
*
* http://www.nethelp.no/net/cisco-hdlc.txt
*
* the address and mask aren't used in requests -
* they're just zero.
*/
break;
case SLARP_REPLY:
ND_PRINT((ndo, "reply %s/%s",
ipaddr_string(ndo, &slarp->un.addr.addr),
ipaddr_string(ndo, &slarp->un.addr.mask)));
break;
case SLARP_KEEPALIVE:
ND_PRINT((ndo, "keepalive: mineseen=0x%08x, yourseen=0x%08x, reliability=0x%04x",
EXTRACT_32BITS(&slarp->un.keep.myseq),
EXTRACT_32BITS(&slarp->un.keep.yourseq),
EXTRACT_16BITS(&slarp->un.keep.rel)));
if (length >= SLARP_MAX_LEN) { /* uptime-stamp is optional */
cp += SLARP_MIN_LEN;
ND_TCHECK2(*cp, 4);
sec = EXTRACT_32BITS(cp) / 1000;
min = sec / 60; sec -= min * 60;
hrs = min / 60; min -= hrs * 60;
days = hrs / 24; hrs -= days * 24;
ND_PRINT((ndo, ", link uptime=%ud%uh%um%us",days,hrs,min,sec));
}
break;
default:
ND_PRINT((ndo, "0x%02x unknown", EXTRACT_32BITS(&slarp->code)));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,cp+4,"\n\t",length-4);
break;
}
if (SLARP_MAX_LEN < length && ndo->ndo_vflag)
ND_PRINT((ndo, ", (trailing junk: %d bytes)", length - SLARP_MAX_LEN));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,cp+4,"\n\t",length-4);
return;
trunc:
ND_PRINT((ndo, "[|slarp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2746_0 |
crossvul-cpp_data_bad_4887_0 | /*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* cJSON */
/* JSON parser in C. */
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cJSON.h"
static const char *global_ep;
const char *cJSON_GetErrorPtr(void) {return global_ep;}
static int cJSON_strcasecmp(const char *s1,const char *s2)
{
if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}
static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
static char* cJSON_strdup(const char* str)
{
size_t len;
char* copy;
len = strlen(str) + 1;
if (!(copy = (char*)cJSON_malloc(len))) return 0;
memcpy(copy,str,len);
return copy;
}
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
if (node) memset(node,0,sizeof(cJSON));
return node;
}
/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
cJSON *next;
while (c)
{
next=c->next;
if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string);
cJSON_free(c);
c=next;
}
}
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item,const char *num)
{
double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
if (*num=='-') sign=-1,num++; /* Has sign? */
if (*num=='0') num++; /* is zero */
if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */
if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */
if (*num=='e' || *num=='E') /* Exponent? */
{ num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */
while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */
}
n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
item->valuedouble=n;
item->valueint=(int)n;
item->type=cJSON_Number;
return num;
}
static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; }
typedef struct {char *buffer; int length; int offset; } printbuffer;
static char* ensure(printbuffer *p,int needed)
{
char *newbuffer;int newsize;
if (!p || !p->buffer) return 0;
needed+=p->offset;
if (needed<=p->length) return p->buffer+p->offset;
newsize=pow2gt(needed);
newbuffer=(char*)cJSON_malloc(newsize);
if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;}
if (newbuffer) memcpy(newbuffer,p->buffer,p->length);
cJSON_free(p->buffer);
p->length=newsize;
p->buffer=newbuffer;
return newbuffer+p->offset;
}
static int update(printbuffer *p)
{
char *str;
if (!p || !p->buffer) return 0;
str=p->buffer+p->offset;
return p->offset+strlen(str);
}
/* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item,printbuffer *p)
{
char *str=0;
double d=item->valuedouble;
if (d==0)
{
if (p) str=ensure(p,2);
else str=(char*)cJSON_malloc(2); /* special case for 0. */
if (str) strcpy(str,"0");
}
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
{
if (p) str=ensure(p,21);
else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
if (str) sprintf(str,"%d",item->valueint);
}
else
{
if (p) str=ensure(p,64);
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
if (str)
{
if (d*0!=0) sprintf(str,"null"); /* This checks for NaN and Infinity */
else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,"%.0f",d);
else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
else sprintf(str,"%f",d);
}
}
return str;
}
static unsigned parse_hex4(const char *str)
{
unsigned h=0;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
return h;
}
/* Parse the input text into an unescaped cstring, and populate item. */
static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const char *parse_string(cJSON *item,const char *str,const char **ep)
{
const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {*ep=str;return 0;} /* not a string! */
while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */
item->type=cJSON_String;
ptr=str+1;ptr2=out;
while (ptr < end_ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */
if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
return ptr;
}
/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr(const char *str,printbuffer *p)
{
const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token;
if (!str)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (!out) return 0;
strcpy(out,"\"\"");
return out;
}
for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0;
if (!flag)
{
len=ptr-str;
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;*ptr2++='\"';
strcpy(ptr2,str);
ptr2[len]='\"';
ptr2[len+1]=0;
return out;
}
ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;ptr=str;
*ptr2++='\"';
while (*ptr)
{
if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
else
{
*ptr2++='\\';
switch (token=*ptr++)
{
case '\\': *ptr2++='\\'; break;
case '\"': *ptr2++='\"'; break;
case '\b': *ptr2++='b'; break;
case '\f': *ptr2++='f'; break;
case '\n': *ptr2++='n'; break;
case '\r': *ptr2++='r'; break;
case '\t': *ptr2++='t'; break;
default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */
}
}
}
*ptr2++='\"';*ptr2++=0;
return out;
}
/* Invote print_string_ptr (which is useful) on an item. */
static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);}
/* Predeclare these prototypes. */
static const char *parse_value(cJSON *item,const char *value,const char **ep);
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_array(cJSON *item,const char *value,const char **ep);
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_object(cJSON *item,const char *value,const char **ep);
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p);
/* Utility to jump whitespace and cr/lf */
static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;}
/* Parse an object - create a new root, and populate. */
cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
{
const char *end=0,**ep=return_parse_end?return_parse_end:&global_ep;
cJSON *c=cJSON_New_Item();
*ep=0;
if (!c) return 0; /* memory fail */
end=parse_value(c,skip(value),ep);
if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);*ep=end;return 0;}}
if (return_parse_end) *return_parse_end=end;
return c;
}
/* Default options for cJSON_Parse */
cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);}
/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);}
char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt)
{
printbuffer p;
p.buffer=(char*)cJSON_malloc(prebuffer);
p.length=prebuffer;
p.offset=0;
return print_value(item,0,fmt,&p);
}
/* Parser core - when encountering text, process appropriately. */
static const char *parse_value(cJSON *item,const char *value,const char **ep)
{
if (!value) return 0; /* Fail on null. */
if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
if (*value=='\"') { return parse_string(item,value,ep); }
if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
if (*value=='[') { return parse_array(item,value,ep); }
if (*value=='{') { return parse_object(item,value,ep); }
*ep=value;return 0; /* failure. */
}
/* Render a value to text. */
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
{
char *out=0;
if (!item) return 0;
if (p)
{
switch ((item->type)&255)
{
case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;}
case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;}
case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;}
case cJSON_Number: out=print_number(item,p);break;
case cJSON_String: out=print_string(item,p);break;
case cJSON_Array: out=print_array(item,depth,fmt,p);break;
case cJSON_Object: out=print_object(item,depth,fmt,p);break;
}
}
else
{
switch ((item->type)&255)
{
case cJSON_NULL: out=cJSON_strdup("null"); break;
case cJSON_False: out=cJSON_strdup("false");break;
case cJSON_True: out=cJSON_strdup("true"); break;
case cJSON_Number: out=print_number(item,0);break;
case cJSON_String: out=print_string(item,0);break;
case cJSON_Array: out=print_array(item,depth,fmt,0);break;
case cJSON_Object: out=print_object(item,depth,fmt,0);break;
}
}
return out;
}
/* Build an array from input text. */
static const char *parse_array(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='[') {*ep=value;return 0;} /* not an array! */
item->type=cJSON_Array;
value=skip(value+1);
if (*value==']') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0; /* memory fail */
value=skip(parse_value(child,skip(value),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_value(child,skip(value+1),ep));
if (!value) return 0; /* memory fail */
}
if (*value==']') return value+1; /* end of array */
*ep=value;return 0; /* malformed. */
}
/* Render an array to text */
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries;
char *out=0,*ptr,*ret;int len=5;
cJSON *child=item->child;
int numentries=0,i=0,fail=0;
size_t tmplen=0;
/* How many entries in the array? */
while (child) numentries++,child=child->next;
/* Explicitly handle numentries==0 */
if (!numentries)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (out) strcpy(out,"[]");
return out;
}
if (p)
{
/* Compose the output array. */
i=p->offset;
ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++;
child=item->child;
while (child && !fail)
{
print_value(child,depth+1,fmt,p);
p->offset=update(p);
if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;}
child=child->next;
}
ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
memset(entries,0,numentries*sizeof(char*));
/* Retrieve all the results: */
child=item->child;
while (child && !fail)
{
ret=print_value(child,depth+1,fmt,0);
entries[i++]=ret;
if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
child=child->next;
}
/* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len);
/* If that fails, we fail. */
if (!out) fail=1;
/* Handle failure. */
if (fail)
{
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries);
return 0;
}
/* Compose the output array. */
*out='[';
ptr=out+1;*ptr=0;
for (i=0;i<numentries;i++)
{
tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen;
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]);
}
cJSON_free(entries);
*ptr++=']';*ptr++=0;
}
return out;
}
/* Build an object from the text. */
static const char *parse_object(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='{') {*ep=value;return 0;} /* not an object! */
item->type=cJSON_Object;
value=skip(value+1);
if (*value=='}') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0;
value=skip(parse_string(child,skip(value),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_string(child,skip(value+1),ep));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {*ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
}
if (*value=='}') return value+1; /* end of array */
*ep=value;return 0; /* malformed. */
}
/* Render an object to text. */
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries=0,**names=0;
char *out=0,*ptr,*ret,*str;int len=7,i=0,j;
cJSON *child=item->child;
int numentries=0,fail=0;
size_t tmplen=0;
/* Count the number of entries. */
while (child) numentries++,child=child->next;
/* Explicitly handle empty object case */
if (!numentries)
{
if (p) out=ensure(p,fmt?depth+4:3);
else out=(char*)cJSON_malloc(fmt?depth+4:3);
if (!out) return 0;
ptr=out;*ptr++='{';
if (fmt) {*ptr++='\n';for (i=0;i<depth;i++) *ptr++='\t';}
*ptr++='}';*ptr++=0;
return out;
}
if (p)
{
/* Compose the output: */
i=p->offset;
len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0;
*ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len;
child=item->child;depth++;
while (child)
{
if (fmt)
{
ptr=ensure(p,depth); if (!ptr) return 0;
for (j=0;j<depth;j++) *ptr++='\t';
p->offset+=depth;
}
print_string_ptr(child->string,p);
p->offset=update(p);
len=fmt?2:1;
ptr=ensure(p,len); if (!ptr) return 0;
*ptr++=':';if (fmt) *ptr++='\t';
p->offset+=len;
print_value(child,depth,fmt,p);
p->offset=update(p);
len=(fmt?1:0)+(child->next?1:0);
ptr=ensure(p,len+1); if (!ptr) return 0;
if (child->next) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
p->offset+=len;
child=child->next;
}
ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0;
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate space for the names and the objects */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
names=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!names) {cJSON_free(entries);return 0;}
memset(entries,0,sizeof(char*)*numentries);
memset(names,0,sizeof(char*)*numentries);
/* Collect all the results into our arrays: */
child=item->child;depth++;if (fmt) len+=depth;
while (child && !fail)
{
names[i]=str=print_string_ptr(child->string,0);
entries[i++]=ret=print_value(child,depth,fmt,0);
if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1;
child=child->next;
}
/* Try to allocate the output string */
if (!fail) out=(char*)cJSON_malloc(len);
if (!out) fail=1;
/* Handle failure */
if (fail)
{
for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
cJSON_free(names);cJSON_free(entries);
return 0;
}
/* Compose the output: */
*out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0;
for (i=0;i<numentries;i++)
{
if (fmt) for (j=0;j<depth;j++) *ptr++='\t';
tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen;
*ptr++=':';if (fmt) *ptr++='\t';
strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
if (i!=numentries-1) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
cJSON_free(names[i]);cJSON_free(entries[i]);
}
cJSON_free(names);cJSON_free(entries);
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr++=0;
}
return out;
}
/* Get Array size/item / object item. */
int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array?array->child:0;while (c && item>0) item--,c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object?object->child:0;while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
int cJSON_HasObjectItem(cJSON *object,const char *string) {return cJSON_GetObjectItem(object,string)?1:0;}
/* Utility for array list handling. */
static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
/* Utility for handling references. */
static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;}
/* Add item to array/object. */
void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);}
void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);}
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));}
void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));}
cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}
void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;}
void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
/* Replace array/object items with new ones. */
void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;}
newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;}
void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}}
/* Create basic types: */
cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);if(!item->valuestring){cJSON_Delete(item);return 0;}}return item;}
cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
/* Create Arrays: */
cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
/* Duplication */
cJSON *cJSON_Duplicate(cJSON *item,int recurse)
{
cJSON *newitem,*cptr,*nptr=0,*newchild;
/* Bail on bad ptr */
if (!item) return 0;
/* Create new item */
newitem=cJSON_New_Item();
if (!newitem) return 0;
/* Copy over all vars */
newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble;
if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}}
if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}}
/* If non-recursive, then we're done! */
if (!recurse) return newitem;
/* Walk the ->next chain for the child. */
cptr=item->child;
while (cptr)
{
newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild) {cJSON_Delete(newitem);return 0;}
if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */
cptr=cptr->next;
}
return newitem;
}
void cJSON_Minify(char *json)
{
char *into=json;
while (*json)
{
if (*json==' ') json++;
else if (*json=='\t') json++; /* Whitespace characters. */
else if (*json=='\r') json++;
else if (*json=='\n') json++;
else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */
else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */
else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */
else *into++=*json++; /* All other characters. */
}
*into=0; /* and null-terminate. */
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4887_0 |
crossvul-cpp_data_bad_3328_2 | /*
Copyright (c) 2013. The YARA Authors. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This module implements a regular expressions engine based on Thompson's
algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html.
What the article names a "thread" has been named a "fiber" in this code, in
order to avoid confusion with operating system threads.
*/
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <yara/limits.h>
#include <yara/globals.h>
#include <yara/utils.h>
#include <yara/mem.h>
#include <yara/re.h>
#include <yara/error.h>
#include <yara/threading.h>
#include <yara/re_lexer.h>
#include <yara/hex_lexer.h>
// Maximum allowed split ID, also limiting the number of split instructions
// allowed in a regular expression. This number can't be increased
// over 255 without changing RE_SPLIT_ID_TYPE.
#define RE_MAX_SPLIT_ID 128
// Maximum stack size for regexp evaluation
#define RE_MAX_STACK 1024
// Maximum code size for a compiled regexp
#define RE_MAX_CODE_SIZE 32768
// Maximum input size scanned by yr_re_exec
#define RE_SCAN_LIMIT 4096
// Maximum number of fibers
#define RE_MAX_FIBERS 1024
#define EMIT_BACKWARDS 0x01
#define EMIT_DONT_SET_FORWARDS_CODE 0x02
#define EMIT_DONT_SET_BACKWARDS_CODE 0x04
typedef struct _RE_REPEAT_ARGS
{
uint16_t min;
uint16_t max;
int32_t offset;
} RE_REPEAT_ARGS;
typedef struct _RE_REPEAT_ANY_ARGS
{
uint16_t min;
uint16_t max;
} RE_REPEAT_ANY_ARGS;
typedef struct _RE_EMIT_CONTEXT {
YR_ARENA* arena;
RE_SPLIT_ID_TYPE next_split_id;
} RE_EMIT_CONTEXT;
typedef struct _RE_FIBER
{
uint8_t* ip; // instruction pointer
int32_t sp; // stack pointer
int32_t rc; // repeat counter
uint16_t stack[RE_MAX_STACK];
struct _RE_FIBER* prev;
struct _RE_FIBER* next;
} RE_FIBER;
typedef struct _RE_FIBER_LIST
{
RE_FIBER* head;
RE_FIBER* tail;
} RE_FIBER_LIST;
typedef struct _RE_FIBER_POOL
{
int fiber_count;
RE_FIBER_LIST fibers;
} RE_FIBER_POOL;
typedef struct _RE_THREAD_STORAGE
{
RE_FIBER_POOL fiber_pool;
} RE_THREAD_STORAGE;
YR_THREAD_STORAGE_KEY thread_storage_key = 0;
//
// yr_re_initialize
//
// Should be called by main thread before any other
// function from this module.
//
int yr_re_initialize(void)
{
return yr_thread_storage_create(&thread_storage_key);
}
//
// yr_re_finalize
//
// Should be called by main thread after every other thread
// stopped using functions from this module.
//
int yr_re_finalize(void)
{
yr_thread_storage_destroy(&thread_storage_key);
thread_storage_key = 0;
return ERROR_SUCCESS;
}
//
// yr_re_finalize_thread
//
// Should be called by every thread using this module
// before exiting.
//
int yr_re_finalize_thread(void)
{
RE_FIBER* fiber;
RE_FIBER* next_fiber;
RE_THREAD_STORAGE* storage;
if (thread_storage_key != 0)
storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
else
return ERROR_SUCCESS;
if (storage != NULL)
{
fiber = storage->fiber_pool.fibers.head;
while (fiber != NULL)
{
next_fiber = fiber->next;
yr_free(fiber);
fiber = next_fiber;
}
yr_free(storage);
}
return yr_thread_storage_set_value(&thread_storage_key, NULL);
}
RE_NODE* yr_re_node_create(
int type,
RE_NODE* left,
RE_NODE* right)
{
RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE));
if (result != NULL)
{
result->type = type;
result->left = left;
result->right = right;
result->greedy = TRUE;
result->forward_code = NULL;
result->backward_code = NULL;
}
return result;
}
void yr_re_node_destroy(
RE_NODE* node)
{
if (node->left != NULL)
yr_re_node_destroy(node->left);
if (node->right != NULL)
yr_re_node_destroy(node->right);
if (node->type == RE_NODE_CLASS)
yr_free(node->class_vector);
yr_free(node);
}
int yr_re_ast_create(
RE_AST** re_ast)
{
*re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
if (*re_ast == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*re_ast)->flags = 0;
(*re_ast)->root_node = NULL;
return ERROR_SUCCESS;
}
void yr_re_ast_destroy(
RE_AST* re_ast)
{
if (re_ast->root_node != NULL)
yr_re_node_destroy(re_ast->root_node);
yr_free(re_ast);
}
//
// yr_re_parse
//
// Parses a regexp but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse(
const char* re_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_re_string(re_string, re_ast, error);
}
//
// yr_re_parse_hex
//
// Parses a hex string but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse_hex(
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_hex_string(hex_string, re_ast, error);
}
//
// yr_re_compile
//
// Parses the regexp and emit its code to the provided code_arena.
//
int yr_re_compile(
const char* re_string,
int flags,
YR_ARENA* code_arena,
RE** re,
RE_ERROR* error)
{
RE_AST* re_ast;
RE _re;
FAIL_ON_ERROR(yr_arena_reserve_memory(
code_arena, sizeof(int64_t) + RE_MAX_CODE_SIZE));
FAIL_ON_ERROR(yr_re_parse(re_string, &re_ast, error));
_re.flags = flags;
FAIL_ON_ERROR_WITH_CLEANUP(
yr_arena_write_data(
code_arena,
&_re,
sizeof(_re),
(void**) re),
yr_re_ast_destroy(re_ast));
FAIL_ON_ERROR_WITH_CLEANUP(
yr_re_ast_emit_code(re_ast, code_arena, FALSE),
yr_re_ast_destroy(re_ast));
yr_re_ast_destroy(re_ast);
return ERROR_SUCCESS;
}
//
// yr_re_match
//
// Verifies if the target string matches the pattern
//
// Args:
// RE* re - A pointer to a compiled regexp
// char* target - Target string
//
// Returns:
// See return codes for yr_re_exec
int yr_re_match(
RE* re,
const char* target)
{
return yr_re_exec(
re->code,
(uint8_t*) target,
strlen(target),
re->flags | RE_FLAGS_SCAN,
NULL,
NULL);
}
//
// yr_re_ast_extract_literal
//
// Verifies if the provided regular expression is just a literal string
// like "abc", "12345", without any wildcard, operator, etc. In that case
// returns the string as a SIZED_STRING, or returns NULL if otherwise.
//
// The caller is responsible for deallocating the returned SIZED_STRING by
// calling yr_free.
//
SIZED_STRING* yr_re_ast_extract_literal(
RE_AST* re_ast)
{
SIZED_STRING* string;
RE_NODE* node = re_ast->root_node;
int i, length = 0;
char tmp;
while (node != NULL)
{
length++;
if (node->type == RE_NODE_LITERAL)
break;
if (node->type != RE_NODE_CONCAT)
return NULL;
if (node->right == NULL ||
node->right->type != RE_NODE_LITERAL)
return NULL;
node = node->left;
}
string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length);
if (string == NULL)
return NULL;
string->length = 0;
node = re_ast->root_node;
while (node->type == RE_NODE_CONCAT)
{
string->c_string[string->length++] = node->right->value;
node = node->left;
}
string->c_string[string->length++] = node->value;
// The string ends up reversed. Reverse it back to its original value.
for (i = 0; i < length / 2; i++)
{
tmp = string->c_string[i];
string->c_string[i] = string->c_string[length - i - 1];
string->c_string[length - i - 1] = tmp;
}
return string;
}
int _yr_re_node_contains_dot_star(
RE_NODE* re_node)
{
if (re_node->type == RE_NODE_STAR && re_node->left->type == RE_NODE_ANY)
return TRUE;
if (re_node->left != NULL && _yr_re_node_contains_dot_star(re_node->left))
return TRUE;
if (re_node->right != NULL && _yr_re_node_contains_dot_star(re_node->right))
return TRUE;
return FALSE;
}
int yr_re_ast_contains_dot_star(
RE_AST* re_ast)
{
return _yr_re_node_contains_dot_star(re_ast->root_node);
}
//
// yr_re_ast_split_at_chaining_point
//
// In some cases splitting a regular expression in two is more efficient that
// having a single regular expression. This happens when the regular expression
// contains a large repetition of any character, for example: /foo.{0,1000}bar/
// In this case the regexp is split in /foo/ and /bar/ where /bar/ is "chained"
// to /foo/. This means that /foo/ and /bar/ are handled as individual regexps
// and when both matches YARA verifies if the distance between the matches
// complies with the {0,1000} restriction.
// This function traverses the regexp's tree looking for nodes where the regxp
// should be split. It expects a left-unbalanced tree where the right child of
// a RE_NODE_CONCAT can't be another RE_NODE_CONCAT. A RE_NODE_CONCAT must be
// always the left child of its parent if the parent is also a RE_NODE_CONCAT.
//
int yr_re_ast_split_at_chaining_point(
RE_AST* re_ast,
RE_AST** result_re_ast,
RE_AST** remainder_re_ast,
int32_t* min_gap,
int32_t* max_gap)
{
RE_NODE* node = re_ast->root_node;
RE_NODE* child = re_ast->root_node->left;
RE_NODE* parent = NULL;
int result;
*result_re_ast = re_ast;
*remainder_re_ast = NULL;
*min_gap = 0;
*max_gap = 0;
while (child != NULL && child->type == RE_NODE_CONCAT)
{
if (child->right != NULL &&
child->right->type == RE_NODE_RANGE_ANY &&
child->right->greedy == FALSE &&
(child->right->start > STRING_CHAINING_THRESHOLD ||
child->right->end > STRING_CHAINING_THRESHOLD))
{
result = yr_re_ast_create(remainder_re_ast);
if (result != ERROR_SUCCESS)
return result;
(*remainder_re_ast)->root_node = child->left;
(*remainder_re_ast)->flags = re_ast->flags;
child->left = NULL;
if (parent != NULL)
parent->left = node->right;
else
(*result_re_ast)->root_node = node->right;
node->right = NULL;
*min_gap = child->right->start;
*max_gap = child->right->end;
yr_re_node_destroy(node);
return ERROR_SUCCESS;
}
parent = node;
node = child;
child = child->left;
}
return ERROR_SUCCESS;
}
int _yr_emit_inst(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t** instruction_addr,
int* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
*code_size = sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint8(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t argument,
uint8_t** instruction_addr,
uint8_t** argument_addr,
int* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint8_t),
(void**) argument_addr));
*code_size = 2 * sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint16_t argument,
uint8_t** instruction_addr,
uint16_t** argument_addr,
int* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint32(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint32_t argument,
uint8_t** instruction_addr,
uint32_t** argument_addr,
int* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint32_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint32_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_int16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
int* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_struct(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
void* structure,
size_t structure_size,
uint8_t** instruction_addr,
void** argument_addr,
int* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
structure,
structure_size,
(void**) argument_addr));
*code_size = sizeof(uint8_t) + structure_size;
return ERROR_SUCCESS;
}
int _yr_emit_split(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
int* code_size)
{
assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B);
if (emit_context->next_split_id == RE_MAX_SPLIT_ID)
return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&emit_context->next_split_id,
sizeof(RE_SPLIT_ID_TYPE),
NULL));
emit_context->next_split_id++;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(RE_SPLIT_ID_TYPE) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_re_emit(
RE_EMIT_CONTEXT* emit_context,
RE_NODE* re_node,
int flags,
uint8_t** code_addr,
int* code_size)
{
int branch_size;
int split_size;
int inst_size;
int jmp_size;
int emit_split;
int emit_repeat;
int emit_prolog;
int emit_epilog;
RE_REPEAT_ARGS repeat_args;
RE_REPEAT_ARGS* repeat_start_args_addr;
RE_REPEAT_ANY_ARGS repeat_any_args;
RE_NODE* left;
RE_NODE* right;
int16_t* split_offset_addr = NULL;
int16_t* jmp_offset_addr = NULL;
uint8_t* instruction_addr = NULL;
*code_size = 0;
switch(re_node->type)
{
case RE_NODE_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint8(
emit_context,
RE_OPCODE_LITERAL,
re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_MASKED_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint16(
emit_context,
RE_OPCODE_MASKED_LITERAL,
re_node->mask << 8 | re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_ANY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_ANY,
&instruction_addr,
code_size));
break;
case RE_NODE_CLASS:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_CLASS,
&instruction_addr,
code_size));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
re_node->class_vector,
32,
NULL));
*code_size += 32;
break;
case RE_NODE_ANCHOR_START:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_START,
&instruction_addr,
code_size));
break;
case RE_NODE_ANCHOR_END:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_END,
&instruction_addr,
code_size));
break;
case RE_NODE_CONCAT:
if (flags & EMIT_BACKWARDS)
{
left = re_node->right;
right = re_node->left;
}
else
{
left = re_node->left;
right = re_node->right;
}
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
break;
case RE_NODE_PLUS:
// Code for e+ looks like:
//
// L1: code for e
// split L1, L2
// L2:
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A,
-branch_size,
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
break;
case RE_NODE_STAR:
// Code for e* looks like:
//
// L1: split L1, L2
// code for e
// jmp L1
// L2:
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
-(branch_size + split_size),
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
// Update split offset.
*split_offset_addr = split_size + branch_size + jmp_size;
break;
case RE_NODE_ALT:
// Code for e1|e2 looks like:
//
// split L1, L2
// L1: code for e1
// jmp L3
// L2: code for e2
// L3:
// Emit a split instruction with offset set to 0 temporarily. Offset
// will be updated after we know the size of the code generated for
// the left node (e1).
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
RE_OPCODE_SPLIT_A,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
0,
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
// Update split offset.
*split_offset_addr = split_size + branch_size + jmp_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Update offset for jmp instruction.
*jmp_offset_addr = branch_size + jmp_size;
break;
case RE_NODE_RANGE_ANY:
repeat_any_args.min = re_node->start;
repeat_any_args.max = re_node->end;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_ANY_GREEDY :
RE_OPCODE_REPEAT_ANY_UNGREEDY,
&repeat_any_args,
sizeof(repeat_any_args),
&instruction_addr,
NULL,
&inst_size));
*code_size += inst_size;
break;
case RE_NODE_RANGE:
// Code for e{n,m} looks like:
//
// code for e --- prolog
// repeat_start n, m, L1 --+
// L0: code for e | repeat
// repeat_end n, m, L0 --+
// L1: split L2, L3 --- split
// L2: code for e --- epilog
// L3:
//
// Not all sections (prolog, repeat, split and epilog) are generated in all
// cases, it depends on the values of n and m. The following table shows
// which sections are generated for the first few values of n and m.
//
// n,m prolog repeat split epilog
// (min,max)
// ---------------------------------------
// 0,0 - - - -
// 0,1 - - X X
// 0,2 - 0,1 X X
// 0,3 - 0,2 X X
// 0,M - 0,M-1 X X
//
// 1,1 X - - -
// 1,2 X - X X
// 1,3 X 0,1 X X
// 1,4 X 1,2 X X
// 1,M X 1,M-2 X X
//
// 2,2 X - - X
// 2,3 X 1,1 X X
// 2,4 X 1,2 X X
// 2,M X 1,M-2 X X
//
// 3,3 X 1,1 - X
// 3,4 X 2,2 X X
// 3,M X 2,M-1 X X
//
// The code can't consists simply in the repeat section, the prolog and
// epilog are required because we can't have atoms pointing to code inside
// the repeat loop. Atoms' forwards_code will point to code in the prolog
// and backwards_code will point to code in the epilog (or in prolog if
// epilog wasn't generated, like in n=1,m=1)
emit_prolog = re_node->start > 0;
emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2;
emit_split = re_node->end > re_node->start;
emit_epilog = re_node->end > re_node->start || re_node->end > 1;
if (emit_prolog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_repeat)
{
repeat_args.min = re_node->start;
repeat_args.max = re_node->end;
if (emit_prolog)
{
repeat_args.max--;
repeat_args.min--;
}
if (emit_split)
repeat_args.max--;
else
repeat_args.min--;
repeat_args.offset = 0;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_START_GREEDY :
RE_OPCODE_REPEAT_START_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
emit_prolog ? NULL : &instruction_addr,
(void**) &repeat_start_args_addr,
&inst_size));
*code_size += inst_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE,
NULL,
&branch_size));
*code_size += branch_size;
repeat_start_args_addr->offset = 2 * inst_size + branch_size;
repeat_args.offset = -branch_size;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_END_GREEDY :
RE_OPCODE_REPEAT_END_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
NULL,
NULL,
&inst_size));
*code_size += inst_size;
}
if (emit_split)
{
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ?
RE_OPCODE_SPLIT_A :
RE_OPCODE_SPLIT_B,
0,
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
}
if (emit_epilog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags,
emit_prolog || emit_repeat ? NULL : &instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_split)
*split_offset_addr = split_size + branch_size;
break;
}
if (flags & EMIT_BACKWARDS)
{
if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE))
re_node->backward_code = instruction_addr + *code_size;
}
else
{
if (!(flags & EMIT_DONT_SET_FORWARDS_CODE))
re_node->forward_code = instruction_addr;
}
if (code_addr != NULL)
*code_addr = instruction_addr;
return ERROR_SUCCESS;
}
int yr_re_ast_emit_code(
RE_AST* re_ast,
YR_ARENA* arena,
int backwards_code)
{
RE_EMIT_CONTEXT emit_context;
int code_size;
int total_size;
// Ensure that we have enough contiguous memory space in the arena to
// contain the regular expression code. The code can't span over multiple
// non-contiguous pages.
FAIL_ON_ERROR(yr_arena_reserve_memory(arena, RE_MAX_CODE_SIZE));
// Emit code for matching the regular expressions forwards.
total_size = 0;
emit_context.arena = arena;
emit_context.next_split_id = 0;
FAIL_ON_ERROR(_yr_re_emit(
&emit_context,
re_ast->root_node,
backwards_code ? EMIT_BACKWARDS : 0,
NULL,
&code_size));
total_size += code_size;
FAIL_ON_ERROR(_yr_emit_inst(
&emit_context,
RE_OPCODE_MATCH,
NULL,
&code_size));
total_size += code_size;
if (total_size > RE_MAX_CODE_SIZE)
return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
return ERROR_SUCCESS;
}
int _yr_re_alloc_storage(
RE_THREAD_STORAGE** storage)
{
*storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
if (*storage == NULL)
{
*storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE));
if (*storage == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*storage)->fiber_pool.fiber_count = 0;
(*storage)->fiber_pool.fibers.head = NULL;
(*storage)->fiber_pool.fibers.tail = NULL;
FAIL_ON_ERROR(
yr_thread_storage_set_value(&thread_storage_key, *storage));
}
return ERROR_SUCCESS;
}
int _yr_re_fiber_create(
RE_FIBER_POOL* fiber_pool,
RE_FIBER** new_fiber)
{
RE_FIBER* fiber;
if (fiber_pool->fibers.head != NULL)
{
fiber = fiber_pool->fibers.head;
fiber_pool->fibers.head = fiber->next;
if (fiber_pool->fibers.tail == fiber)
fiber_pool->fibers.tail = NULL;
}
else
{
if (fiber_pool->fiber_count == RE_MAX_FIBERS)
return ERROR_TOO_MANY_RE_FIBERS;
fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER));
if (fiber == NULL)
return ERROR_INSUFFICIENT_MEMORY;
fiber_pool->fiber_count++;
}
fiber->ip = NULL;
fiber->sp = -1;
fiber->rc = -1;
fiber->next = NULL;
fiber->prev = NULL;
*new_fiber = fiber;
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_append
//
// Appends 'fiber' to 'fiber_list'
//
void _yr_re_fiber_append(
RE_FIBER_LIST* fiber_list,
RE_FIBER* fiber)
{
assert(fiber->prev == NULL);
assert(fiber->next == NULL);
fiber->prev = fiber_list->tail;
if (fiber_list->tail != NULL)
fiber_list->tail->next = fiber;
fiber_list->tail = fiber;
if (fiber_list->head == NULL)
fiber_list->head = fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
}
//
// _yr_re_fiber_exists
//
// Verifies if a fiber with the same properties (ip, rc, sp, and stack values)
// than 'target_fiber' exists in 'fiber_list'. The list is iterated from
// the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not
// taken into account.
//
int _yr_re_fiber_exists(
RE_FIBER_LIST* fiber_list,
RE_FIBER* target_fiber,
RE_FIBER* last_fiber)
{
RE_FIBER* fiber = fiber_list->head;
int equal_stacks;
int i;
if (last_fiber == NULL)
return FALSE;
while (fiber != last_fiber->next)
{
if (fiber->ip == target_fiber->ip &&
fiber->sp == target_fiber->sp &&
fiber->rc == target_fiber->rc)
{
equal_stacks = TRUE;
for (i = 0; i <= fiber->sp; i++)
{
if (fiber->stack[i] != target_fiber->stack[i])
{
equal_stacks = FALSE;
break;
}
}
if (equal_stacks)
return TRUE;
}
fiber = fiber->next;
}
return FALSE;
}
//
// _yr_re_fiber_split
//
// Clones a fiber in fiber_list and inserts the cloned fiber just after.
// the original one. If fiber_list is:
//
// f1 -> f2 -> f3 -> f4
//
// Splitting f2 will result in:
//
// f1 -> f2 -> cloned f2 -> f3 -> f4
//
int _yr_re_fiber_split(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber,
RE_FIBER** new_fiber)
{
int32_t i;
FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber));
(*new_fiber)->sp = fiber->sp;
(*new_fiber)->ip = fiber->ip;
(*new_fiber)->rc = fiber->rc;
for (i = 0; i <= fiber->sp; i++)
(*new_fiber)->stack[i] = fiber->stack[i];
(*new_fiber)->next = fiber->next;
(*new_fiber)->prev = fiber;
if (fiber->next != NULL)
fiber->next->prev = *new_fiber;
fiber->next = *new_fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = *new_fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_kill
//
// Kills a given fiber by removing it from the fiber list and putting it
// in the fiber pool.
//
RE_FIBER* _yr_re_fiber_kill(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* next_fiber = fiber->next;
if (fiber->prev != NULL)
fiber->prev->next = next_fiber;
if (next_fiber != NULL)
next_fiber->prev = fiber->prev;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = fiber->prev;
if (fiber_list->head == fiber)
fiber_list->head = next_fiber;
fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
fiber_pool->fibers.tail = fiber;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
return next_fiber;
}
//
// _yr_re_fiber_kill_tail
//
// Kills all fibers from the given one up to the end of the fiber list.
//
void _yr_re_fiber_kill_tail(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* prev_fiber = fiber->prev;
if (prev_fiber != NULL)
prev_fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
fiber_pool->fibers.tail = fiber_list->tail;
fiber_list->tail = prev_fiber;
if (fiber_list->head == fiber)
fiber_list->head = NULL;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
}
//
// _yr_re_fiber_kill_tail
//
// Kills all fibers in the fiber list.
//
void _yr_re_fiber_kill_all(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool)
{
if (fiber_list->head != NULL)
_yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head);
}
//
// _yr_re_fiber_sync
//
// Executes a fiber until reaching an "matching" instruction. A "matching"
// instruction is one that actually reads a byte from the input and performs
// some matching. If the fiber reaches a split instruction, the new fiber is
// also synced.
//
int _yr_re_fiber_sync(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber_to_sync)
{
// A array for keeping track of which split instructions has been already
// executed. Each split instruction within a regexp has an associated ID
// between 0 and RE_MAX_SPLIT_ID. Keeping track of executed splits is
// required to avoid infinite loops in regexps like (a*)* or (a|)*
RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID];
RE_SPLIT_ID_TYPE splits_executed_count = 0;
RE_SPLIT_ID_TYPE split_id, splits_executed_idx;
int split_already_executed;
RE_REPEAT_ARGS* repeat_args;
RE_REPEAT_ANY_ARGS* repeat_any_args;
RE_FIBER* fiber;
RE_FIBER* last;
RE_FIBER* prev;
RE_FIBER* next;
RE_FIBER* branch_a;
RE_FIBER* branch_b;
fiber = fiber_to_sync;
prev = fiber_to_sync->prev;
last = fiber_to_sync->next;
while(fiber != last)
{
uint8_t opcode = *fiber->ip;
switch(opcode)
{
case RE_OPCODE_SPLIT_A:
case RE_OPCODE_SPLIT_B:
split_id = *(RE_SPLIT_ID_TYPE*)(fiber->ip + 1);
split_already_executed = FALSE;
for (splits_executed_idx = 0;
splits_executed_idx < splits_executed_count;
splits_executed_idx++)
{
if (split_id == splits_executed[splits_executed_idx])
{
split_already_executed = TRUE;
break;
}
}
if (split_already_executed)
{
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
}
else
{
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
// With RE_OPCODE_SPLIT_A the current fiber continues at the next
// instruction in the stream (branch A), while the newly created
// fiber starts at the address indicated by the instruction (branch B)
// RE_OPCODE_SPLIT_B has the opposite behavior.
if (opcode == RE_OPCODE_SPLIT_B)
yr_swap(branch_a, branch_b, RE_FIBER*);
// Branch A continues at the next instruction
branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3);
// Branch B adds the offset encoded in the opcode to its instruction
// pointer.
branch_b->ip += *(int16_t*)(
branch_b->ip
+ 1 // opcode size
+ sizeof(RE_SPLIT_ID_TYPE));
splits_executed[splits_executed_count] = split_id;
splits_executed_count++;
}
break;
case RE_OPCODE_REPEAT_START_GREEDY:
case RE_OPCODE_REPEAT_START_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
assert(repeat_args->max > 0);
branch_a = fiber;
if (repeat_args->min == 0)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_b->ip += repeat_args->offset;
}
branch_a->stack[++branch_a->sp] = 0;
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_END_GREEDY:
case RE_OPCODE_REPEAT_END_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
fiber->stack[fiber->sp]++;
if (fiber->stack[fiber->sp] < repeat_args->min)
{
fiber->ip += repeat_args->offset;
break;
}
branch_a = fiber;
if (fiber->stack[fiber->sp] < repeat_args->max)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_END_GREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->sp--;
branch_b->ip += repeat_args->offset;
}
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(fiber->ip + 1);
// If repetition counter (rc) is -1 it means that we are reaching this
// instruction from the previous one in the instructions stream. In
// this case let's initialize the counter to 0 and start looping.
if (fiber->rc == -1)
fiber->rc = 0;
if (fiber->rc < repeat_any_args->min)
{
// Increase repetition counter and continue with next fiber. The
// instruction pointer for this fiber is not incremented yet, this
// fiber spins in this same instruction until reaching the minimum
// number of repetitions.
fiber->rc++;
fiber = fiber->next;
}
else if (fiber->rc < repeat_any_args->max)
{
// Once the minimum number of repetitions are matched one fiber
// remains spinning in this instruction until reaching the maximum
// number of repetitions while new fibers are created. New fibers
// start executing at the next instruction.
next = fiber->next;
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->rc++;
branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
branch_b->rc = -1;
_yr_re_fiber_sync(fiber_list, fiber_pool, branch_b);
fiber = next;
}
else
{
// When the maximum number of repetitions is reached the fiber keeps
// executing at the next instruction. The repetition counter is set
// to -1 indicating that we are not spinning in a repeat instruction
// anymore.
fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
fiber->rc = -1;
}
break;
case RE_OPCODE_JUMP:
fiber->ip += *(int16_t*)(fiber->ip + 1);
break;
default:
if (_yr_re_fiber_exists(fiber_list, fiber, prev))
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
else
fiber = fiber->next;
}
}
return ERROR_SUCCESS;
}
//
// yr_re_exec
//
// Executes a regular expression
//
// Args:
// uint8_t* re_code - Regexp code be executed
// uint8_t* input - Pointer to input data
// size_t input_size - Input data size
// int flags - Flags:
// RE_FLAGS_SCAN
// RE_FLAGS_BACKWARDS
// RE_FLAGS_EXHAUSTIVE
// RE_FLAGS_WIDE
// RE_FLAGS_NOT_AT_START
// RE_FLAGS_NO_CASE
// RE_FLAGS_DOT_ALL
// RE_MATCH_CALLBACK_FUNC callback - Callback function
// void* callback_args - Callback argument
//
// Returns:
// Integer indicating the number of matching bytes, including 0 when
// matching an empty regexp. Negative values indicate:
// -1 No match
// -2 Not enough memory
// -3 Too many matches
// -4 Too many fibers
// -5 Unknown fatal error
int yr_re_exec(
uint8_t* re_code,
uint8_t* input_data,
size_t input_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args)
{
uint8_t* ip;
uint8_t* input;
uint8_t mask;
uint8_t value;
RE_FIBER_LIST fibers;
RE_THREAD_STORAGE* storage;
RE_FIBER* fiber;
RE_FIBER* next_fiber;
int error;
int bytes_matched;
int max_bytes_matched;
int match;
int character_size;
int input_incr;
int kill;
int action;
int result = -1;
#define ACTION_NONE 0
#define ACTION_CONTINUE 1
#define ACTION_KILL 2
#define ACTION_KILL_TAIL 3
#define prolog if (bytes_matched >= max_bytes_matched) \
{ \
action = ACTION_KILL; \
break; \
}
#define fail_if_error(e) switch (e) { \
case ERROR_INSUFFICIENT_MEMORY: \
return -2; \
case ERROR_TOO_MANY_RE_FIBERS: \
return -4; \
}
if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS)
return -2;
if (flags & RE_FLAGS_WIDE)
character_size = 2;
else
character_size = 1;
input = input_data;
input_incr = character_size;
if (flags & RE_FLAGS_BACKWARDS)
{
input -= character_size;
input_incr = -input_incr;
}
max_bytes_matched = (int) yr_min(input_size, RE_SCAN_LIMIT);
// Round down max_bytes_matched to a multiple of character_size, this way if
// character_size is 2 and input_size is odd we are ignoring the
// extra byte which can't match anyways.
max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size;
bytes_matched = 0;
error = _yr_re_fiber_create(&storage->fiber_pool, &fiber);
fail_if_error(error);
fiber->ip = re_code;
fibers.head = fiber;
fibers.tail = fiber;
error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber);
fail_if_error(error);
while (fibers.head != NULL)
{
fiber = fibers.head;
while(fiber != NULL)
{
ip = fiber->ip;
action = ACTION_NONE;
switch(*ip)
{
case RE_OPCODE_ANY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
// The instruction pointer is not incremented here. The current fiber
// spins in this instruction until reaching the required number of
// repetitions. The code controlling the number of repetitions is in
// _yr_re_fiber_sync.
break;
case RE_OPCODE_LITERAL:
prolog;
if (flags & RE_FLAGS_NO_CASE)
match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)];
else
match = (*input == *(ip + 1));
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 2;
break;
case RE_OPCODE_MASKED_LITERAL:
prolog;
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
// We don't need to take into account the case-insensitive
// case because this opcode is only used with hex strings,
// which can't be case-insensitive.
match = ((*input & mask) == value);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 3;
break;
case RE_OPCODE_CLASS:
prolog;
match = CHAR_IN_CLASS(*input, ip + 1);
if (!match && (flags & RE_FLAGS_NO_CASE))
match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 33;
break;
case RE_OPCODE_WORD_CHAR:
prolog;
match = IS_WORD_CHAR(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_WORD_CHAR:
prolog;
match = !IS_WORD_CHAR(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_SPACE:
case RE_OPCODE_NON_SPACE:
prolog;
switch(*input)
{
case ' ':
case '\t':
case '\r':
case '\n':
case '\v':
case '\f':
match = TRUE;
break;
default:
match = FALSE;
}
if (*ip == RE_OPCODE_NON_SPACE)
match = !match;
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_DIGIT:
prolog;
match = isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_DIGIT:
prolog;
match = !isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_WORD_BOUNDARY:
case RE_OPCODE_NON_WORD_BOUNDARY:
if (bytes_matched == 0 &&
!(flags & RE_FLAGS_NOT_AT_START) &&
!(flags & RE_FLAGS_BACKWARDS))
match = TRUE;
else if (bytes_matched >= max_bytes_matched)
match = TRUE;
else if (IS_WORD_CHAR(*(input - input_incr)) != IS_WORD_CHAR(*input))
match = TRUE;
else
match = FALSE;
if (*ip == RE_OPCODE_NON_WORD_BOUNDARY)
match = !match;
action = match ? ACTION_CONTINUE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_START:
if (flags & RE_FLAGS_BACKWARDS)
kill = input_size > (size_t) bytes_matched;
else
kill = (flags & RE_FLAGS_NOT_AT_START) || (bytes_matched != 0);
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_END:
kill = flags & RE_FLAGS_BACKWARDS ||
input_size > (size_t) bytes_matched;
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH:
result = bytes_matched;
if (flags & RE_FLAGS_EXHAUSTIVE)
{
if (callback != NULL)
{
int cb_result;
if (flags & RE_FLAGS_BACKWARDS)
cb_result = callback(
input + character_size,
bytes_matched,
flags,
callback_args);
else
cb_result = callback(
input_data,
bytes_matched,
flags,
callback_args);
switch(cb_result)
{
case ERROR_INSUFFICIENT_MEMORY:
return -2;
case ERROR_TOO_MANY_MATCHES:
return -3;
default:
if (cb_result != ERROR_SUCCESS)
return -4;
}
}
action = ACTION_KILL;
}
else
{
action = ACTION_KILL_TAIL;
}
break;
default:
assert(FALSE);
}
switch(action)
{
case ACTION_KILL:
fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber);
break;
case ACTION_KILL_TAIL:
_yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber);
fiber = NULL;
break;
case ACTION_CONTINUE:
error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber);
fail_if_error(error);
break;
default:
next_fiber = fiber->next;
error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber);
fail_if_error(error);
fiber = next_fiber;
}
}
if (flags & RE_FLAGS_WIDE &&
bytes_matched < max_bytes_matched &&
*(input + 1) != 0)
{
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool);
}
input += input_incr;
bytes_matched += character_size;
if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched)
{
error = _yr_re_fiber_create(&storage->fiber_pool, &fiber);
fail_if_error(error);
fiber->ip = re_code;
_yr_re_fiber_append(&fibers, fiber);
error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber);
fail_if_error(error);
}
}
return result;
}
int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched = input_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
int cb_result = callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args);
switch(cb_result)
{
case ERROR_INSUFFICIENT_MEMORY:
return -2;
case ERROR_TOO_MANY_MATCHES:
return -3;
default:
if (cb_result != ERROR_SUCCESS)
return -4;
}
break;
}
else
{
return bytes_matched;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
next_input = input + i * input_incr;
if (bytes_matched + i >= max_bytes_matched)
break;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
return -1;
}
void _yr_re_print_node(
RE_NODE* re_node)
{
int i;
if (re_node == NULL)
return;
switch(re_node->type)
{
case RE_NODE_ALT:
printf("Alt(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_CONCAT:
printf("Cat(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_STAR:
printf("Star(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_PLUS:
printf("Plus(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_LITERAL:
printf("Lit(%02X)", re_node->value);
break;
case RE_NODE_MASKED_LITERAL:
printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask);
break;
case RE_NODE_WORD_CHAR:
printf("WordChar");
break;
case RE_NODE_NON_WORD_CHAR:
printf("NonWordChar");
break;
case RE_NODE_SPACE:
printf("Space");
break;
case RE_NODE_NON_SPACE:
printf("NonSpace");
break;
case RE_NODE_DIGIT:
printf("Digit");
break;
case RE_NODE_NON_DIGIT:
printf("NonDigit");
break;
case RE_NODE_ANY:
printf("Any");
break;
case RE_NODE_RANGE:
printf("Range(%d-%d, ", re_node->start, re_node->end);
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_CLASS:
printf("Class(");
for (i = 0; i < 256; i++)
if (CHAR_IN_CLASS(i, re_node->class_vector))
printf("%02X,", i);
printf(")");
break;
default:
printf("???");
break;
}
}
void yr_re_print(
RE_AST* re_ast)
{
_yr_re_print_node(re_ast->root_node);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3328_2 |
crossvul-cpp_data_bad_3396_0 | /*
Copyright (c) 2013. The YARA Authors. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This module implements a regular expressions engine based on Thompson's
algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html.
What the article names a "thread" has been named a "fiber" in this code, in
order to avoid confusion with operating system threads.
*/
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <yara/limits.h>
#include <yara/globals.h>
#include <yara/utils.h>
#include <yara/mem.h>
#include <yara/re.h>
#include <yara/error.h>
#include <yara/threading.h>
#include <yara/re_lexer.h>
#include <yara/hex_lexer.h>
#define EMIT_BACKWARDS 0x01
#define EMIT_DONT_SET_FORWARDS_CODE 0x02
#define EMIT_DONT_SET_BACKWARDS_CODE 0x04
typedef struct _RE_REPEAT_ARGS
{
uint16_t min;
uint16_t max;
int32_t offset;
} RE_REPEAT_ARGS;
typedef struct _RE_REPEAT_ANY_ARGS
{
uint16_t min;
uint16_t max;
} RE_REPEAT_ANY_ARGS;
typedef struct _RE_EMIT_CONTEXT {
YR_ARENA* arena;
RE_SPLIT_ID_TYPE next_split_id;
} RE_EMIT_CONTEXT;
typedef struct _RE_FIBER
{
uint8_t* ip; // instruction pointer
int32_t sp; // stack pointer
int32_t rc; // repeat counter
uint16_t stack[RE_MAX_STACK];
struct _RE_FIBER* prev;
struct _RE_FIBER* next;
} RE_FIBER;
typedef struct _RE_FIBER_LIST
{
RE_FIBER* head;
RE_FIBER* tail;
} RE_FIBER_LIST;
typedef struct _RE_FIBER_POOL
{
int fiber_count;
RE_FIBER_LIST fibers;
} RE_FIBER_POOL;
typedef struct _RE_THREAD_STORAGE
{
RE_FIBER_POOL fiber_pool;
} RE_THREAD_STORAGE;
YR_THREAD_STORAGE_KEY thread_storage_key = 0;
#define CHAR_IN_CLASS(chr, cls) \
((cls)[(chr) / 8] & 1 << ((chr) % 8))
int _yr_re_is_word_char(
uint8_t* input,
uint8_t character_size)
{
int result = ((isalnum(*input) || (*input) == '_'));
if (character_size == 2)
result = result && (*(input + 1) == 0);
return result;
}
//
// yr_re_initialize
//
// Should be called by main thread before any other
// function from this module.
//
int yr_re_initialize(void)
{
return yr_thread_storage_create(&thread_storage_key);
}
//
// yr_re_finalize
//
// Should be called by main thread after every other thread
// stopped using functions from this module.
//
int yr_re_finalize(void)
{
yr_thread_storage_destroy(&thread_storage_key);
thread_storage_key = 0;
return ERROR_SUCCESS;
}
//
// yr_re_finalize_thread
//
// Should be called by every thread using this module
// before exiting.
//
int yr_re_finalize_thread(void)
{
RE_FIBER* fiber;
RE_FIBER* next_fiber;
RE_THREAD_STORAGE* storage;
if (thread_storage_key != 0)
storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
else
return ERROR_SUCCESS;
if (storage != NULL)
{
fiber = storage->fiber_pool.fibers.head;
while (fiber != NULL)
{
next_fiber = fiber->next;
yr_free(fiber);
fiber = next_fiber;
}
yr_free(storage);
}
return yr_thread_storage_set_value(&thread_storage_key, NULL);
}
RE_NODE* yr_re_node_create(
int type,
RE_NODE* left,
RE_NODE* right)
{
RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE));
if (result != NULL)
{
result->type = type;
result->left = left;
result->right = right;
result->greedy = TRUE;
result->forward_code = NULL;
result->backward_code = NULL;
}
return result;
}
void yr_re_node_destroy(
RE_NODE* node)
{
if (node->left != NULL)
yr_re_node_destroy(node->left);
if (node->right != NULL)
yr_re_node_destroy(node->right);
if (node->type == RE_NODE_CLASS)
yr_free(node->class_vector);
yr_free(node);
}
int yr_re_ast_create(
RE_AST** re_ast)
{
*re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
if (*re_ast == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*re_ast)->flags = 0;
(*re_ast)->levels = 0;
(*re_ast)->root_node = NULL;
return ERROR_SUCCESS;
}
void yr_re_ast_destroy(
RE_AST* re_ast)
{
if (re_ast->root_node != NULL)
yr_re_node_destroy(re_ast->root_node);
yr_free(re_ast);
}
//
// yr_re_parse
//
// Parses a regexp but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse(
const char* re_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_re_string(re_string, re_ast, error);
}
//
// yr_re_parse_hex
//
// Parses a hex string but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse_hex(
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_hex_string(hex_string, re_ast, error);
}
//
// yr_re_compile
//
// Parses the regexp and emit its code to the provided code_arena.
//
int yr_re_compile(
const char* re_string,
int flags,
YR_ARENA* code_arena,
RE** re,
RE_ERROR* error)
{
RE_AST* re_ast;
RE _re;
FAIL_ON_ERROR(yr_arena_reserve_memory(
code_arena, sizeof(int64_t) + RE_MAX_CODE_SIZE));
FAIL_ON_ERROR(yr_re_parse(re_string, &re_ast, error));
_re.flags = flags;
FAIL_ON_ERROR_WITH_CLEANUP(
yr_arena_write_data(
code_arena,
&_re,
sizeof(_re),
(void**) re),
yr_re_ast_destroy(re_ast));
FAIL_ON_ERROR_WITH_CLEANUP(
yr_re_ast_emit_code(re_ast, code_arena, FALSE),
yr_re_ast_destroy(re_ast));
yr_re_ast_destroy(re_ast);
return ERROR_SUCCESS;
}
//
// yr_re_match
//
// Verifies if the target string matches the pattern
//
// Args:
// RE* re - A pointer to a compiled regexp
// char* target - Target string
//
// Returns:
// See return codes for yr_re_exec
int yr_re_match(
RE* re,
const char* target)
{
int result;
yr_re_exec(
re->code,
(uint8_t*) target,
strlen(target),
0,
re->flags | RE_FLAGS_SCAN,
NULL,
NULL,
&result);
return result;
}
//
// yr_re_ast_extract_literal
//
// Verifies if the provided regular expression is just a literal string
// like "abc", "12345", without any wildcard, operator, etc. In that case
// returns the string as a SIZED_STRING, or returns NULL if otherwise.
//
// The caller is responsible for deallocating the returned SIZED_STRING by
// calling yr_free.
//
SIZED_STRING* yr_re_ast_extract_literal(
RE_AST* re_ast)
{
SIZED_STRING* string;
RE_NODE* node = re_ast->root_node;
int i, length = 0;
char tmp;
while (node != NULL)
{
length++;
if (node->type == RE_NODE_LITERAL)
break;
if (node->type != RE_NODE_CONCAT)
return NULL;
if (node->right == NULL ||
node->right->type != RE_NODE_LITERAL)
return NULL;
node = node->left;
}
string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length);
if (string == NULL)
return NULL;
string->length = 0;
node = re_ast->root_node;
while (node->type == RE_NODE_CONCAT)
{
string->c_string[string->length++] = node->right->value;
node = node->left;
}
string->c_string[string->length++] = node->value;
// The string ends up reversed. Reverse it back to its original value.
for (i = 0; i < length / 2; i++)
{
tmp = string->c_string[i];
string->c_string[i] = string->c_string[length - i - 1];
string->c_string[length - i - 1] = tmp;
}
return string;
}
int _yr_re_node_contains_dot_star(
RE_NODE* re_node)
{
if (re_node->type == RE_NODE_STAR && re_node->left->type == RE_NODE_ANY)
return TRUE;
if (re_node->left != NULL && _yr_re_node_contains_dot_star(re_node->left))
return TRUE;
if (re_node->right != NULL && _yr_re_node_contains_dot_star(re_node->right))
return TRUE;
return FALSE;
}
int yr_re_ast_contains_dot_star(
RE_AST* re_ast)
{
return _yr_re_node_contains_dot_star(re_ast->root_node);
}
//
// yr_re_ast_split_at_chaining_point
//
// In some cases splitting a regular expression in two is more efficient that
// having a single regular expression. This happens when the regular expression
// contains a large repetition of any character, for example: /foo.{0,1000}bar/
// In this case the regexp is split in /foo/ and /bar/ where /bar/ is "chained"
// to /foo/. This means that /foo/ and /bar/ are handled as individual regexps
// and when both matches YARA verifies if the distance between the matches
// complies with the {0,1000} restriction.
// This function traverses the regexp's tree looking for nodes where the regxp
// should be split. It expects a left-unbalanced tree where the right child of
// a RE_NODE_CONCAT can't be another RE_NODE_CONCAT. A RE_NODE_CONCAT must be
// always the left child of its parent if the parent is also a RE_NODE_CONCAT.
//
int yr_re_ast_split_at_chaining_point(
RE_AST* re_ast,
RE_AST** result_re_ast,
RE_AST** remainder_re_ast,
int32_t* min_gap,
int32_t* max_gap)
{
RE_NODE* node = re_ast->root_node;
RE_NODE* child = re_ast->root_node->left;
RE_NODE* parent = NULL;
int result;
*result_re_ast = re_ast;
*remainder_re_ast = NULL;
*min_gap = 0;
*max_gap = 0;
while (child != NULL && child->type == RE_NODE_CONCAT)
{
if (child->right != NULL &&
child->right->type == RE_NODE_RANGE_ANY &&
child->right->greedy == FALSE &&
(child->right->start > STRING_CHAINING_THRESHOLD ||
child->right->end > STRING_CHAINING_THRESHOLD))
{
result = yr_re_ast_create(remainder_re_ast);
if (result != ERROR_SUCCESS)
return result;
(*remainder_re_ast)->root_node = child->left;
(*remainder_re_ast)->flags = re_ast->flags;
child->left = NULL;
if (parent != NULL)
parent->left = node->right;
else
(*result_re_ast)->root_node = node->right;
node->right = NULL;
*min_gap = child->right->start;
*max_gap = child->right->end;
yr_re_node_destroy(node);
return ERROR_SUCCESS;
}
parent = node;
node = child;
child = child->left;
}
return ERROR_SUCCESS;
}
int _yr_emit_inst(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t** instruction_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
*code_size = sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint8(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t argument,
uint8_t** instruction_addr,
uint8_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint8_t),
(void**) argument_addr));
*code_size = 2 * sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint16_t argument,
uint8_t** instruction_addr,
uint16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint32(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint32_t argument,
uint8_t** instruction_addr,
uint32_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint32_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint32_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_int16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_struct(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
void* structure,
size_t structure_size,
uint8_t** instruction_addr,
void** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
structure,
structure_size,
(void**) argument_addr));
*code_size = sizeof(uint8_t) + structure_size;
return ERROR_SUCCESS;
}
int _yr_emit_split(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
size_t* code_size)
{
assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B);
if (emit_context->next_split_id == RE_MAX_SPLIT_ID)
return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&emit_context->next_split_id,
sizeof(RE_SPLIT_ID_TYPE),
NULL));
emit_context->next_split_id++;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(RE_SPLIT_ID_TYPE) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_re_emit(
RE_EMIT_CONTEXT* emit_context,
RE_NODE* re_node,
int flags,
uint8_t** code_addr,
size_t* code_size)
{
size_t branch_size;
size_t split_size;
size_t inst_size;
size_t jmp_size;
int emit_split;
int emit_repeat;
int emit_prolog;
int emit_epilog;
RE_REPEAT_ARGS repeat_args;
RE_REPEAT_ARGS* repeat_start_args_addr;
RE_REPEAT_ANY_ARGS repeat_any_args;
RE_NODE* left;
RE_NODE* right;
int16_t* split_offset_addr = NULL;
int16_t* jmp_offset_addr = NULL;
uint8_t* instruction_addr = NULL;
*code_size = 0;
switch(re_node->type)
{
case RE_NODE_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint8(
emit_context,
RE_OPCODE_LITERAL,
re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_MASKED_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint16(
emit_context,
RE_OPCODE_MASKED_LITERAL,
re_node->mask << 8 | re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_ANY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_ANY,
&instruction_addr,
code_size));
break;
case RE_NODE_CLASS:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_CLASS,
&instruction_addr,
code_size));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
re_node->class_vector,
32,
NULL));
*code_size += 32;
break;
case RE_NODE_ANCHOR_START:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_START,
&instruction_addr,
code_size));
break;
case RE_NODE_ANCHOR_END:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_END,
&instruction_addr,
code_size));
break;
case RE_NODE_CONCAT:
if (flags & EMIT_BACKWARDS)
{
left = re_node->right;
right = re_node->left;
}
else
{
left = re_node->left;
right = re_node->right;
}
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
break;
case RE_NODE_PLUS:
// Code for e+ looks like:
//
// L1: code for e
// split L1, L2
// L2:
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A,
-((int16_t) branch_size),
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
break;
case RE_NODE_STAR:
// Code for e* looks like:
//
// L1: split L1, L2
// code for e
// jmp L1
// L2:
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
-((uint16_t)(branch_size + split_size)),
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
assert(split_size + branch_size + jmp_size < INT16_MAX);
// Update split offset.
*split_offset_addr = (int16_t) (split_size + branch_size + jmp_size);
break;
case RE_NODE_ALT:
// Code for e1|e2 looks like:
//
// split L1, L2
// L1: code for e1
// jmp L3
// L2: code for e2
// L3:
// Emit a split instruction with offset set to 0 temporarily. Offset
// will be updated after we know the size of the code generated for
// the left node (e1).
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
RE_OPCODE_SPLIT_A,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
0,
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
assert(split_size + branch_size + jmp_size < INT16_MAX);
// Update split offset.
*split_offset_addr = (int16_t) (split_size + branch_size + jmp_size);
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
assert(branch_size + jmp_size < INT16_MAX);
// Update offset for jmp instruction.
*jmp_offset_addr = (int16_t) (branch_size + jmp_size);
break;
case RE_NODE_RANGE_ANY:
repeat_any_args.min = re_node->start;
repeat_any_args.max = re_node->end;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_ANY_GREEDY :
RE_OPCODE_REPEAT_ANY_UNGREEDY,
&repeat_any_args,
sizeof(repeat_any_args),
&instruction_addr,
NULL,
&inst_size));
*code_size += inst_size;
break;
case RE_NODE_RANGE:
// Code for e{n,m} looks like:
//
// code for e --- prolog
// repeat_start n, m, L1 --+
// L0: code for e | repeat
// repeat_end n, m, L0 --+
// L1: split L2, L3 --- split
// L2: code for e --- epilog
// L3:
//
// Not all sections (prolog, repeat, split and epilog) are generated in all
// cases, it depends on the values of n and m. The following table shows
// which sections are generated for the first few values of n and m.
//
// n,m prolog repeat split epilog
// (min,max)
// ---------------------------------------
// 0,0 - - - -
// 0,1 - - X X
// 0,2 - 0,1 X X
// 0,3 - 0,2 X X
// 0,M - 0,M-1 X X
//
// 1,1 X - - -
// 1,2 X - X X
// 1,3 X 0,1 X X
// 1,4 X 1,2 X X
// 1,M X 1,M-2 X X
//
// 2,2 X - - X
// 2,3 X 1,1 X X
// 2,4 X 1,2 X X
// 2,M X 1,M-2 X X
//
// 3,3 X 1,1 - X
// 3,4 X 2,2 X X
// 3,M X 2,M-1 X X
//
// The code can't consists simply in the repeat section, the prolog and
// epilog are required because we can't have atoms pointing to code inside
// the repeat loop. Atoms' forwards_code will point to code in the prolog
// and backwards_code will point to code in the epilog (or in prolog if
// epilog wasn't generated, like in n=1,m=1)
emit_prolog = re_node->start > 0;
emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2;
emit_split = re_node->end > re_node->start;
emit_epilog = re_node->end > re_node->start || re_node->end > 1;
if (emit_prolog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_repeat)
{
repeat_args.min = re_node->start;
repeat_args.max = re_node->end;
if (emit_prolog)
{
repeat_args.max--;
repeat_args.min--;
}
if (emit_split)
repeat_args.max--;
else
repeat_args.min--;
repeat_args.offset = 0;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_START_GREEDY :
RE_OPCODE_REPEAT_START_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
emit_prolog ? NULL : &instruction_addr,
(void**) &repeat_start_args_addr,
&inst_size));
*code_size += inst_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE,
NULL,
&branch_size));
*code_size += branch_size;
repeat_start_args_addr->offset = (int32_t)(2 * inst_size + branch_size);
repeat_args.offset = -((int32_t) branch_size);
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_END_GREEDY :
RE_OPCODE_REPEAT_END_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
NULL,
NULL,
&inst_size));
*code_size += inst_size;
}
if (emit_split)
{
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ?
RE_OPCODE_SPLIT_A :
RE_OPCODE_SPLIT_B,
0,
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
}
if (emit_epilog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags,
emit_prolog || emit_repeat ? NULL : &instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_split)
{
assert(split_size + branch_size < INT16_MAX);
*split_offset_addr = (int16_t) (split_size + branch_size);
}
break;
}
if (flags & EMIT_BACKWARDS)
{
if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE))
re_node->backward_code = instruction_addr + *code_size;
}
else
{
if (!(flags & EMIT_DONT_SET_FORWARDS_CODE))
re_node->forward_code = instruction_addr;
}
if (code_addr != NULL)
*code_addr = instruction_addr;
return ERROR_SUCCESS;
}
int yr_re_ast_emit_code(
RE_AST* re_ast,
YR_ARENA* arena,
int backwards_code)
{
RE_EMIT_CONTEXT emit_context;
size_t code_size;
size_t total_size;
// Ensure that we have enough contiguous memory space in the arena to
// contain the regular expression code. The code can't span over multiple
// non-contiguous pages.
FAIL_ON_ERROR(yr_arena_reserve_memory(arena, RE_MAX_CODE_SIZE));
// Emit code for matching the regular expressions forwards.
total_size = 0;
emit_context.arena = arena;
emit_context.next_split_id = 0;
FAIL_ON_ERROR(_yr_re_emit(
&emit_context,
re_ast->root_node,
backwards_code ? EMIT_BACKWARDS : 0,
NULL,
&code_size));
total_size += code_size;
FAIL_ON_ERROR(_yr_emit_inst(
&emit_context,
RE_OPCODE_MATCH,
NULL,
&code_size));
total_size += code_size;
if (total_size > RE_MAX_CODE_SIZE)
return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
return ERROR_SUCCESS;
}
int _yr_re_alloc_storage(
RE_THREAD_STORAGE** storage)
{
*storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
if (*storage == NULL)
{
*storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE));
if (*storage == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*storage)->fiber_pool.fiber_count = 0;
(*storage)->fiber_pool.fibers.head = NULL;
(*storage)->fiber_pool.fibers.tail = NULL;
FAIL_ON_ERROR(
yr_thread_storage_set_value(&thread_storage_key, *storage));
}
return ERROR_SUCCESS;
}
int _yr_re_fiber_create(
RE_FIBER_POOL* fiber_pool,
RE_FIBER** new_fiber)
{
RE_FIBER* fiber;
if (fiber_pool->fibers.head != NULL)
{
fiber = fiber_pool->fibers.head;
fiber_pool->fibers.head = fiber->next;
if (fiber_pool->fibers.tail == fiber)
fiber_pool->fibers.tail = NULL;
}
else
{
if (fiber_pool->fiber_count == RE_MAX_FIBERS)
return ERROR_TOO_MANY_RE_FIBERS;
fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER));
if (fiber == NULL)
return ERROR_INSUFFICIENT_MEMORY;
fiber_pool->fiber_count++;
}
fiber->ip = NULL;
fiber->sp = -1;
fiber->rc = -1;
fiber->next = NULL;
fiber->prev = NULL;
*new_fiber = fiber;
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_append
//
// Appends 'fiber' to 'fiber_list'
//
void _yr_re_fiber_append(
RE_FIBER_LIST* fiber_list,
RE_FIBER* fiber)
{
assert(fiber->prev == NULL);
assert(fiber->next == NULL);
fiber->prev = fiber_list->tail;
if (fiber_list->tail != NULL)
fiber_list->tail->next = fiber;
fiber_list->tail = fiber;
if (fiber_list->head == NULL)
fiber_list->head = fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
}
//
// _yr_re_fiber_exists
//
// Verifies if a fiber with the same properties (ip, rc, sp, and stack values)
// than 'target_fiber' exists in 'fiber_list'. The list is iterated from
// the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not
// taken into account.
//
int _yr_re_fiber_exists(
RE_FIBER_LIST* fiber_list,
RE_FIBER* target_fiber,
RE_FIBER* last_fiber)
{
RE_FIBER* fiber = fiber_list->head;
int equal_stacks;
int i;
if (last_fiber == NULL)
return FALSE;
while (fiber != last_fiber->next)
{
if (fiber->ip == target_fiber->ip &&
fiber->sp == target_fiber->sp &&
fiber->rc == target_fiber->rc)
{
equal_stacks = TRUE;
for (i = 0; i <= fiber->sp; i++)
{
if (fiber->stack[i] != target_fiber->stack[i])
{
equal_stacks = FALSE;
break;
}
}
if (equal_stacks)
return TRUE;
}
fiber = fiber->next;
}
return FALSE;
}
//
// _yr_re_fiber_split
//
// Clones a fiber in fiber_list and inserts the cloned fiber just after.
// the original one. If fiber_list is:
//
// f1 -> f2 -> f3 -> f4
//
// Splitting f2 will result in:
//
// f1 -> f2 -> cloned f2 -> f3 -> f4
//
int _yr_re_fiber_split(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber,
RE_FIBER** new_fiber)
{
int32_t i;
FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber));
(*new_fiber)->sp = fiber->sp;
(*new_fiber)->ip = fiber->ip;
(*new_fiber)->rc = fiber->rc;
for (i = 0; i <= fiber->sp; i++)
(*new_fiber)->stack[i] = fiber->stack[i];
(*new_fiber)->next = fiber->next;
(*new_fiber)->prev = fiber;
if (fiber->next != NULL)
fiber->next->prev = *new_fiber;
fiber->next = *new_fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = *new_fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_kill
//
// Kills a given fiber by removing it from the fiber list and putting it
// in the fiber pool.
//
RE_FIBER* _yr_re_fiber_kill(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* next_fiber = fiber->next;
if (fiber->prev != NULL)
fiber->prev->next = next_fiber;
if (next_fiber != NULL)
next_fiber->prev = fiber->prev;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = fiber->prev;
if (fiber_list->head == fiber)
fiber_list->head = next_fiber;
fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
fiber_pool->fibers.tail = fiber;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
return next_fiber;
}
//
// _yr_re_fiber_kill_tail
//
// Kills all fibers from the given one up to the end of the fiber list.
//
void _yr_re_fiber_kill_tail(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* prev_fiber = fiber->prev;
if (prev_fiber != NULL)
prev_fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
fiber_pool->fibers.tail = fiber_list->tail;
fiber_list->tail = prev_fiber;
if (fiber_list->head == fiber)
fiber_list->head = NULL;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
}
//
// _yr_re_fiber_kill_all
//
// Kills all fibers in the fiber list.
//
void _yr_re_fiber_kill_all(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool)
{
if (fiber_list->head != NULL)
_yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head);
}
//
// _yr_re_fiber_sync
//
// Executes a fiber until reaching an "matching" instruction. A "matching"
// instruction is one that actually reads a byte from the input and performs
// some matching. If the fiber reaches a split instruction, the new fiber is
// also synced.
//
int _yr_re_fiber_sync(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber_to_sync)
{
// A array for keeping track of which split instructions has been already
// executed. Each split instruction within a regexp has an associated ID
// between 0 and RE_MAX_SPLIT_ID. Keeping track of executed splits is
// required to avoid infinite loops in regexps like (a*)* or (a|)*
RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID];
RE_SPLIT_ID_TYPE splits_executed_count = 0;
RE_SPLIT_ID_TYPE split_id, splits_executed_idx;
int split_already_executed;
RE_REPEAT_ARGS* repeat_args;
RE_REPEAT_ANY_ARGS* repeat_any_args;
RE_FIBER* fiber;
RE_FIBER* last;
RE_FIBER* prev;
RE_FIBER* next;
RE_FIBER* branch_a;
RE_FIBER* branch_b;
fiber = fiber_to_sync;
prev = fiber_to_sync->prev;
last = fiber_to_sync->next;
while(fiber != last)
{
uint8_t opcode = *fiber->ip;
switch(opcode)
{
case RE_OPCODE_SPLIT_A:
case RE_OPCODE_SPLIT_B:
split_id = *(RE_SPLIT_ID_TYPE*)(fiber->ip + 1);
split_already_executed = FALSE;
for (splits_executed_idx = 0;
splits_executed_idx < splits_executed_count;
splits_executed_idx++)
{
if (split_id == splits_executed[splits_executed_idx])
{
split_already_executed = TRUE;
break;
}
}
if (split_already_executed)
{
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
}
else
{
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
// With RE_OPCODE_SPLIT_A the current fiber continues at the next
// instruction in the stream (branch A), while the newly created
// fiber starts at the address indicated by the instruction (branch B)
// RE_OPCODE_SPLIT_B has the opposite behavior.
if (opcode == RE_OPCODE_SPLIT_B)
yr_swap(branch_a, branch_b, RE_FIBER*);
// Branch A continues at the next instruction
branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3);
// Branch B adds the offset encoded in the opcode to its instruction
// pointer.
branch_b->ip += *(int16_t*)(
branch_b->ip
+ 1 // opcode size
+ sizeof(RE_SPLIT_ID_TYPE));
splits_executed[splits_executed_count] = split_id;
splits_executed_count++;
}
break;
case RE_OPCODE_REPEAT_START_GREEDY:
case RE_OPCODE_REPEAT_START_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
assert(repeat_args->max > 0);
branch_a = fiber;
if (repeat_args->min == 0)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_b->ip += repeat_args->offset;
}
branch_a->stack[++branch_a->sp] = 0;
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_END_GREEDY:
case RE_OPCODE_REPEAT_END_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
fiber->stack[fiber->sp]++;
if (fiber->stack[fiber->sp] < repeat_args->min)
{
fiber->ip += repeat_args->offset;
break;
}
branch_a = fiber;
if (fiber->stack[fiber->sp] < repeat_args->max)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_END_GREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->sp--;
branch_b->ip += repeat_args->offset;
}
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(fiber->ip + 1);
// If repetition counter (rc) is -1 it means that we are reaching this
// instruction from the previous one in the instructions stream. In
// this case let's initialize the counter to 0 and start looping.
if (fiber->rc == -1)
fiber->rc = 0;
if (fiber->rc < repeat_any_args->min)
{
// Increase repetition counter and continue with next fiber. The
// instruction pointer for this fiber is not incremented yet, this
// fiber spins in this same instruction until reaching the minimum
// number of repetitions.
fiber->rc++;
fiber = fiber->next;
}
else if (fiber->rc < repeat_any_args->max)
{
// Once the minimum number of repetitions are matched one fiber
// remains spinning in this instruction until reaching the maximum
// number of repetitions while new fibers are created. New fibers
// start executing at the next instruction.
next = fiber->next;
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->rc++;
branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
branch_b->rc = -1;
FAIL_ON_ERROR(_yr_re_fiber_sync(
fiber_list, fiber_pool, branch_b));
fiber = next;
}
else
{
// When the maximum number of repetitions is reached the fiber keeps
// executing at the next instruction. The repetition counter is set
// to -1 indicating that we are not spinning in a repeat instruction
// anymore.
fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
fiber->rc = -1;
}
break;
case RE_OPCODE_JUMP:
fiber->ip += *(int16_t*)(fiber->ip + 1);
break;
default:
if (_yr_re_fiber_exists(fiber_list, fiber, prev))
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
else
fiber = fiber->next;
}
}
return ERROR_SUCCESS;
}
//
// yr_re_exec
//
// Executes a regular expression. The specified regular expression will try to
// match the data starting at the address specified by "input". The "input"
// pointer can point to any address inside a memory buffer. Arguments
// "input_forwards_size" and "input_backwards_size" indicate how many bytes
// can be accesible starting at "input" and going forwards and backwards
// respectively.
//
// <--- input_backwards_size -->|<----------- input_forwards_size -------->
// |-------- memory buffer -----------------------------------------------|
// ^
// input
//
// Args:
// uint8_t* re_code - Regexp code be executed
// uint8_t* input - Pointer to input data
// size_t input_forwards_size - Number of accessible bytes starting at
// "input" and going forwards.
// size_t input_backwards_size - Number of accessible bytes starting at
// "input" and going backwards
// int flags - Flags:
// RE_FLAGS_SCAN
// RE_FLAGS_BACKWARDS
// RE_FLAGS_EXHAUSTIVE
// RE_FLAGS_WIDE
// RE_FLAGS_NO_CASE
// RE_FLAGS_DOT_ALL
// RE_MATCH_CALLBACK_FUNC callback - Callback function
// void* callback_args - Callback argument
// int* matches - Pointer to an integer receiving the
// number of matching bytes. Notice that
// 0 means a zero-length match, while no
// matches is -1.
// Returns:
// ERROR_SUCCESS or any other error code.
int yr_re_exec(
uint8_t* re_code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
uint8_t* ip;
uint8_t* input;
uint8_t mask;
uint8_t value;
uint8_t character_size;
RE_FIBER_LIST fibers;
RE_THREAD_STORAGE* storage;
RE_FIBER* fiber;
RE_FIBER* next_fiber;
int bytes_matched;
int max_bytes_matched;
int match;
int input_incr;
int kill;
int action;
#define ACTION_NONE 0
#define ACTION_CONTINUE 1
#define ACTION_KILL 2
#define ACTION_KILL_TAIL 3
#define prolog { \
if ((bytes_matched >= max_bytes_matched) || \
(character_size == 2 && *(input + 1) != 0)) \
{ \
action = ACTION_KILL; \
break; \
} \
}
if (matches != NULL)
*matches = -1;
if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS)
return -2;
if (flags & RE_FLAGS_WIDE)
character_size = 2;
else
character_size = 1;
input = input_data;
input_incr = character_size;
if (flags & RE_FLAGS_BACKWARDS)
{
max_bytes_matched = (int) yr_min(input_backwards_size, RE_SCAN_LIMIT);
input -= character_size;
input_incr = -input_incr;
}
else
{
max_bytes_matched = (int) yr_min(input_forwards_size, RE_SCAN_LIMIT);
}
// Round down max_bytes_matched to a multiple of character_size, this way if
// character_size is 2 and max_bytes_matched is odd we are ignoring the
// extra byte which can't match anyways.
max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size;
bytes_matched = 0;
FAIL_ON_ERROR(_yr_re_fiber_create(&storage->fiber_pool, &fiber));
fiber->ip = re_code;
fibers.head = fiber;
fibers.tail = fiber;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
while (fibers.head != NULL)
{
fiber = fibers.head;
while(fiber != NULL)
{
ip = fiber->ip;
action = ACTION_NONE;
switch(*ip)
{
case RE_OPCODE_ANY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
// The instruction pointer is not incremented here. The current fiber
// spins in this instruction until reaching the required number of
// repetitions. The code controlling the number of repetitions is in
// _yr_re_fiber_sync.
break;
case RE_OPCODE_LITERAL:
prolog;
if (flags & RE_FLAGS_NO_CASE)
match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)];
else
match = (*input == *(ip + 1));
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 2;
break;
case RE_OPCODE_MASKED_LITERAL:
prolog;
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
// We don't need to take into account the case-insensitive
// case because this opcode is only used with hex strings,
// which can't be case-insensitive.
match = ((*input & mask) == value);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 3;
break;
case RE_OPCODE_CLASS:
prolog;
match = CHAR_IN_CLASS(*input, ip + 1);
if (!match && (flags & RE_FLAGS_NO_CASE))
match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 33;
break;
case RE_OPCODE_WORD_CHAR:
prolog;
match = _yr_re_is_word_char(input, character_size);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_WORD_CHAR:
prolog;
match = !_yr_re_is_word_char(input, character_size);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_SPACE:
case RE_OPCODE_NON_SPACE:
prolog;
switch(*input)
{
case ' ':
case '\t':
case '\r':
case '\n':
case '\v':
case '\f':
match = TRUE;
break;
default:
match = FALSE;
}
if (*ip == RE_OPCODE_NON_SPACE)
match = !match;
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_DIGIT:
prolog;
match = isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_DIGIT:
prolog;
match = !isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_WORD_BOUNDARY:
case RE_OPCODE_NON_WORD_BOUNDARY:
if (bytes_matched == 0 && input_backwards_size < character_size)
{
match = TRUE;
}
else if (bytes_matched >= max_bytes_matched)
{
match = TRUE;
}
else
{
assert(input < input_data + input_forwards_size);
assert(input >= input_data - input_backwards_size);
assert(input - input_incr < input_data + input_forwards_size);
assert(input - input_incr >= input_data - input_backwards_size);
match = _yr_re_is_word_char(input, character_size) != \
_yr_re_is_word_char(input - input_incr, character_size);
}
if (*ip == RE_OPCODE_NON_WORD_BOUNDARY)
match = !match;
action = match ? ACTION_CONTINUE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_START:
if (flags & RE_FLAGS_BACKWARDS)
kill = input_backwards_size > (size_t) bytes_matched;
else
kill = input_backwards_size > 0 || (bytes_matched != 0);
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_END:
kill = flags & RE_FLAGS_BACKWARDS ||
input_forwards_size > (size_t) bytes_matched;
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH:
if (matches != NULL)
*matches = bytes_matched;
if (flags & RE_FLAGS_EXHAUSTIVE)
{
if (callback != NULL)
{
if (flags & RE_FLAGS_BACKWARDS)
{
FAIL_ON_ERROR_WITH_CLEANUP(
callback(
input + character_size,
bytes_matched,
flags,
callback_args),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
else
{
FAIL_ON_ERROR_WITH_CLEANUP(
callback(
input_data,
bytes_matched,
flags,
callback_args),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
}
action = ACTION_KILL;
}
else
{
action = ACTION_KILL_TAIL;
}
break;
default:
assert(FALSE);
}
switch(action)
{
case ACTION_KILL:
fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber);
break;
case ACTION_KILL_TAIL:
_yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber);
fiber = NULL;
break;
case ACTION_CONTINUE:
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
break;
default:
next_fiber = fiber->next;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
fiber = next_fiber;
}
}
input += input_incr;
bytes_matched += character_size;
if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched)
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_create(&storage->fiber_pool, &fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
fiber->ip = re_code;
_yr_re_fiber_append(&fibers, fiber);
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
}
return ERROR_SUCCESS;
}
int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
next_input = input + i * input_incr;
if (bytes_matched + i >= max_bytes_matched)
break;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
void _yr_re_print_node(
RE_NODE* re_node)
{
int i;
if (re_node == NULL)
return;
switch(re_node->type)
{
case RE_NODE_ALT:
printf("Alt(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_CONCAT:
printf("Cat(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_STAR:
printf("Star(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_PLUS:
printf("Plus(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_LITERAL:
printf("Lit(%02X)", re_node->value);
break;
case RE_NODE_MASKED_LITERAL:
printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask);
break;
case RE_NODE_WORD_CHAR:
printf("WordChar");
break;
case RE_NODE_NON_WORD_CHAR:
printf("NonWordChar");
break;
case RE_NODE_SPACE:
printf("Space");
break;
case RE_NODE_NON_SPACE:
printf("NonSpace");
break;
case RE_NODE_DIGIT:
printf("Digit");
break;
case RE_NODE_NON_DIGIT:
printf("NonDigit");
break;
case RE_NODE_ANY:
printf("Any");
break;
case RE_NODE_RANGE:
printf("Range(%d-%d, ", re_node->start, re_node->end);
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_CLASS:
printf("Class(");
for (i = 0; i < 256; i++)
if (CHAR_IN_CLASS(i, re_node->class_vector))
printf("%02X,", i);
printf(")");
break;
default:
printf("???");
break;
}
}
void yr_re_print(
RE_AST* re_ast)
{
_yr_re_print_node(re_ast->root_node);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3396_0 |
crossvul-cpp_data_bad_2648_1 | /*
* 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"},
};
#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;
uint8_t 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: %d, RES: %d, Sel: %d",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07)));
ND_PRINT((ndo, "Protocol ID: %d", 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 < 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_2648_1 |
crossvul-cpp_data_good_5211_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO PPPP EEEEE RRRR TTTTT Y Y %
% P P R R O O P P E R R T Y Y %
% PPPP RRRR O O PPPP EEE RRRR T Y %
% P R R O O P E R R T Y %
% P R R OOO P EEEEE R R T Y %
% %
% %
% MagickCore Property Methods %
% %
% Software Design %
% Cristy %
% March 2000 %
% %
% %
% 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/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/compare.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/fx.h"
#include "MagickCore/fx-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/layer.h"
#include "MagickCore/locale-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/montage.h"
#include "MagickCore/option.h"
#include "MagickCore/policy.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/signature.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/token-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS2_LCMS2_H)
#include <lcms2/lcms2.h>
#elif defined(MAGICKCORE_HAVE_LCMS2_H)
#include "lcms2.h"
#elif defined(MAGICKCORE_HAVE_LCMS_LCMS_H)
#include <lcms/lcms.h>
#else
#include "lcms.h"
#endif
#endif
/*
Define declarations.
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
#define cmsUInt32Number DWORD
#endif
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o p e r t i e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProperties() clones all the image properties to another image.
%
% The format of the CloneImageProperties method is:
%
% MagickBooleanType CloneImageProperties(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProperties(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->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
clone_image->filename);
(void) CopyMagickString(image->filename,clone_image->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,clone_image->magick_filename,
MagickPathExtent);
image->compression=clone_image->compression;
image->quality=clone_image->quality;
image->depth=clone_image->depth;
image->alpha_color=clone_image->alpha_color;
image->background_color=clone_image->background_color;
image->border_color=clone_image->border_color;
image->transparent_color=clone_image->transparent_color;
image->gamma=clone_image->gamma;
image->chromaticity=clone_image->chromaticity;
image->rendering_intent=clone_image->rendering_intent;
image->black_point_compensation=clone_image->black_point_compensation;
image->units=clone_image->units;
image->montage=(char *) NULL;
image->directory=(char *) NULL;
(void) CloneString(&image->geometry,clone_image->geometry);
image->offset=clone_image->offset;
image->resolution.x=clone_image->resolution.x;
image->resolution.y=clone_image->resolution.y;
image->page=clone_image->page;
image->tile_offset=clone_image->tile_offset;
image->extract_info=clone_image->extract_info;
image->filter=clone_image->filter;
image->fuzz=clone_image->fuzz;
image->intensity=clone_image->intensity;
image->interlace=clone_image->interlace;
image->interpolate=clone_image->interpolate;
image->endian=clone_image->endian;
image->gravity=clone_image->gravity;
image->compose=clone_image->compose;
image->orientation=clone_image->orientation;
image->scene=clone_image->scene;
image->dispose=clone_image->dispose;
image->delay=clone_image->delay;
image->ticks_per_second=clone_image->ticks_per_second;
image->iterations=clone_image->iterations;
image->total_colors=clone_image->total_colors;
image->taint=clone_image->taint;
image->progress_monitor=clone_image->progress_monitor;
image->client_data=clone_image->client_data;
image->start_loop=clone_image->start_loop;
image->error=clone_image->error;
image->signature=clone_image->signature;
if (clone_image->properties != (void *) NULL)
{
if (image->properties != (void *) NULL)
DestroyImageProperties(image);
image->properties=CloneSplayTree((SplayTreeInfo *)
clone_image->properties,(void *(*)(void *)) ConstantString,
(void *(*)(void *)) ConstantString);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e f i n e I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineImageProperty() associates an assignment string of the form
% "key=value" with an artifact or options. It is equivelent to
% SetImageProperty()
%
% The format of the DefineImageProperty method is:
%
% MagickBooleanType DefineImageProperty(Image *image,const char *property,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DefineImageProperty(Image *image,
const char *property,ExceptionInfo *exception)
{
char
key[MagickPathExtent],
value[MagickPathExtent];
register char
*p;
assert(image != (Image *) NULL);
assert(property != (const char *) NULL);
(void) CopyMagickString(key,property,MagickPathExtent-1);
for (p=key; *p != '\0'; p++)
if (*p == '=')
break;
*value='\0';
if (*p == '=')
(void) CopyMagickString(value,p+1,MagickPathExtent);
*p='\0';
return(SetImageProperty(image,key,value,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProperty() deletes an image property.
%
% The format of the DeleteImageProperty method is:
%
% MagickBooleanType DeleteImageProperty(Image *image,const char *property)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
*/
MagickExport MagickBooleanType DeleteImageProperty(Image *image,
const char *property)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
return(MagickFalse);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->properties,property));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o p e r t i e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProperties() destroys all properties and associated memory
% attached to the given image.
%
% The format of the DestroyDefines method is:
%
% void DestroyImageProperties(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProperties(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties != (void *) NULL)
image->properties=(void *) DestroySplayTree((SplayTreeInfo *)
image->properties);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r m a t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatImageProperty() permits formatted property/value pairs to be saved as
% an image property.
%
% The format of the FormatImageProperty method is:
%
% MagickBooleanType FormatImageProperty(Image *image,const char *property,
% const char *format,...)
%
% A description of each parameter follows.
%
% o image: The image.
%
% o property: The attribute property.
%
% o format: A string describing the format to use to write the remaining
% arguments.
%
*/
MagickExport MagickBooleanType FormatImageProperty(Image *image,
const char *property,const char *format,...)
{
char
value[MagickPathExtent];
ExceptionInfo
*exception;
MagickBooleanType
status;
ssize_t
n;
va_list
operands;
va_start(operands,format);
n=FormatLocaleStringList(value,MagickPathExtent,format,operands);
(void) n;
va_end(operands);
exception=AcquireExceptionInfo();
status=SetImageProperty(image,property,value,exception);
exception=DestroyExceptionInfo(exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProperty() gets a value associated with an image property.
%
% This includes, profile prefixes, such as "exif:", "iptc:" and "8bim:"
% It does not handle non-prifile prefixes, such as "fx:", "option:", or
% "artifact:".
%
% The returned string is stored as a properity of the same name for faster
% lookup later. It should NOT be freed by the caller.
%
% The format of the GetImageProperty method is:
%
% const char *GetImageProperty(const Image *image,const char *key,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o key: the key.
%
% o exception: return any errors or warnings in this structure.
%
*/
static char
*TracePSClippath(const unsigned char *,size_t),
*TraceSVGClippath(const unsigned char *,size_t,const size_t,
const size_t);
static MagickBooleanType GetIPTCProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
*message;
const StringInfo
*profile;
long
count,
dataset,
record;
register ssize_t
i;
size_t
length;
profile=GetImageProfile(image,"iptc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=sscanf(key,"IPTC:%ld:%ld",&dataset,&record);
if (count != 2)
return(MagickFalse);
attribute=(char *) NULL;
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=(ssize_t) length)
{
length=1;
if ((ssize_t) GetStringInfoDatum(profile)[i] != 0x1c)
continue;
length=(size_t) (GetStringInfoDatum(profile)[i+3] << 8);
length|=GetStringInfoDatum(profile)[i+4];
if (((long) GetStringInfoDatum(profile)[i+1] == dataset) &&
((long) GetStringInfoDatum(profile)[i+2] == record))
{
message=(char *) NULL;
if (~length >= 1)
message=(char *) AcquireQuantumMemory(length+1UL,sizeof(*message));
if (message != (char *) NULL)
{
(void) CopyMagickString(message,(char *) GetStringInfoDatum(
profile)+i+5,length+1);
(void) ConcatenateString(&attribute,message);
(void) ConcatenateString(&attribute,";");
message=DestroyString(message);
}
}
i+=5;
}
if ((attribute == (char *) NULL) || (*attribute == ';'))
{
if (attribute != (char *) NULL)
attribute=DestroyString(attribute);
return(MagickFalse);
}
attribute[strlen(attribute)-1]='\0';
(void) SetImageProperty((Image *) image,key,(const char *) attribute,
exception);
attribute=DestroyString(attribute);
return(MagickTrue);
}
static inline int ReadPropertyByte(const unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
unsigned int
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
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 short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
static MagickBooleanType Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((count < 0) || ((size_t) count > length))
{
length=0;
continue;
}
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
}
static inline signed int ReadPropertySignedLong(const EndianType endian,
const 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 unsigned int ReadPropertyUnsignedLong(const EndianType endian,
const unsigned char *buffer)
{
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];
return(value & 0xffffffff);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
return(value & 0xffffffff);
}
static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
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 unsigned short ReadPropertyUnsignedShort(const EndianType endian,
const unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
return(value & 0xffff);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
return(value & 0xffff);
}
static MagickBooleanType GetEXIFProperty(const Image *image,
const char *property,ExceptionInfo *exception)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define EXIF_FMT_BYTE 1
#define EXIF_FMT_STRING 2
#define EXIF_FMT_USHORT 3
#define EXIF_FMT_ULONG 4
#define EXIF_FMT_URATIONAL 5
#define EXIF_FMT_SBYTE 6
#define EXIF_FMT_UNDEFINED 7
#define EXIF_FMT_SSHORT 8
#define EXIF_FMT_SLONG 9
#define EXIF_FMT_SRATIONAL 10
#define EXIF_FMT_SINGLE 11
#define EXIF_FMT_DOUBLE 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_GPS_OFFSET 0x8825
#define TAG_INTEROP_OFFSET 0xa005
#define EXIFMultipleValues(size,format,arg) \
{ \
ssize_t \
component; \
\
size_t \
length; \
\
unsigned char \
*p1; \
\
length=0; \
p1=p; \
for (component=0; component < components; component++) \
{ \
length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \
format", ",arg); \
if (length >= (MagickPathExtent-1)) \
length=MagickPathExtent-1; \
p1+=size; \
} \
if (length > 1) \
buffer[length-2]='\0'; \
value=AcquireString(buffer); \
}
#define EXIFMultipleFractions(size,format,arg1,arg2) \
{ \
ssize_t \
component; \
\
size_t \
length; \
\
unsigned char \
*p1; \
\
length=0; \
p1=p; \
for (component=0; component < components; component++) \
{ \
length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \
format", ",(arg1),(arg2)); \
if (length >= (MagickPathExtent-1)) \
length=MagickPathExtent-1; \
p1+=size; \
} \
if (length > 1) \
buffer[length-2]='\0'; \
value=AcquireString(buffer); \
}
typedef struct _DirectoryInfo
{
const unsigned char
*directory;
size_t
entry;
ssize_t
offset;
} DirectoryInfo;
typedef struct _TagInfo
{
size_t
tag;
const char
*description;
} TagInfo;
static TagInfo
EXIFTag[] =
{
{ 0x001, "exif:InteroperabilityIndex" },
{ 0x002, "exif:InteroperabilityVersion" },
{ 0x100, "exif:ImageWidth" },
{ 0x101, "exif:ImageLength" },
{ 0x102, "exif:BitsPerSample" },
{ 0x103, "exif:Compression" },
{ 0x106, "exif:PhotometricInterpretation" },
{ 0x10a, "exif:FillOrder" },
{ 0x10d, "exif:DocumentName" },
{ 0x10e, "exif:ImageDescription" },
{ 0x10f, "exif:Make" },
{ 0x110, "exif:Model" },
{ 0x111, "exif:StripOffsets" },
{ 0x112, "exif:Orientation" },
{ 0x115, "exif:SamplesPerPixel" },
{ 0x116, "exif:RowsPerStrip" },
{ 0x117, "exif:StripByteCounts" },
{ 0x11a, "exif:XResolution" },
{ 0x11b, "exif:YResolution" },
{ 0x11c, "exif:PlanarConfiguration" },
{ 0x11d, "exif:PageName" },
{ 0x11e, "exif:XPosition" },
{ 0x11f, "exif:YPosition" },
{ 0x118, "exif:MinSampleValue" },
{ 0x119, "exif:MaxSampleValue" },
{ 0x120, "exif:FreeOffsets" },
{ 0x121, "exif:FreeByteCounts" },
{ 0x122, "exif:GrayResponseUnit" },
{ 0x123, "exif:GrayResponseCurve" },
{ 0x124, "exif:T4Options" },
{ 0x125, "exif:T6Options" },
{ 0x128, "exif:ResolutionUnit" },
{ 0x12d, "exif:TransferFunction" },
{ 0x131, "exif:Software" },
{ 0x132, "exif:DateTime" },
{ 0x13b, "exif:Artist" },
{ 0x13e, "exif:WhitePoint" },
{ 0x13f, "exif:PrimaryChromaticities" },
{ 0x140, "exif:ColorMap" },
{ 0x141, "exif:HalfToneHints" },
{ 0x142, "exif:TileWidth" },
{ 0x143, "exif:TileLength" },
{ 0x144, "exif:TileOffsets" },
{ 0x145, "exif:TileByteCounts" },
{ 0x14a, "exif:SubIFD" },
{ 0x14c, "exif:InkSet" },
{ 0x14d, "exif:InkNames" },
{ 0x14e, "exif:NumberOfInks" },
{ 0x150, "exif:DotRange" },
{ 0x151, "exif:TargetPrinter" },
{ 0x152, "exif:ExtraSample" },
{ 0x153, "exif:SampleFormat" },
{ 0x154, "exif:SMinSampleValue" },
{ 0x155, "exif:SMaxSampleValue" },
{ 0x156, "exif:TransferRange" },
{ 0x157, "exif:ClipPath" },
{ 0x158, "exif:XClipPathUnits" },
{ 0x159, "exif:YClipPathUnits" },
{ 0x15a, "exif:Indexed" },
{ 0x15b, "exif:JPEGTables" },
{ 0x15f, "exif:OPIProxy" },
{ 0x200, "exif:JPEGProc" },
{ 0x201, "exif:JPEGInterchangeFormat" },
{ 0x202, "exif:JPEGInterchangeFormatLength" },
{ 0x203, "exif:JPEGRestartInterval" },
{ 0x205, "exif:JPEGLosslessPredictors" },
{ 0x206, "exif:JPEGPointTransforms" },
{ 0x207, "exif:JPEGQTables" },
{ 0x208, "exif:JPEGDCTables" },
{ 0x209, "exif:JPEGACTables" },
{ 0x211, "exif:YCbCrCoefficients" },
{ 0x212, "exif:YCbCrSubSampling" },
{ 0x213, "exif:YCbCrPositioning" },
{ 0x214, "exif:ReferenceBlackWhite" },
{ 0x2bc, "exif:ExtensibleMetadataPlatform" },
{ 0x301, "exif:Gamma" },
{ 0x302, "exif:ICCProfileDescriptor" },
{ 0x303, "exif:SRGBRenderingIntent" },
{ 0x320, "exif:ImageTitle" },
{ 0x5001, "exif:ResolutionXUnit" },
{ 0x5002, "exif:ResolutionYUnit" },
{ 0x5003, "exif:ResolutionXLengthUnit" },
{ 0x5004, "exif:ResolutionYLengthUnit" },
{ 0x5005, "exif:PrintFlags" },
{ 0x5006, "exif:PrintFlagsVersion" },
{ 0x5007, "exif:PrintFlagsCrop" },
{ 0x5008, "exif:PrintFlagsBleedWidth" },
{ 0x5009, "exif:PrintFlagsBleedWidthScale" },
{ 0x500A, "exif:HalftoneLPI" },
{ 0x500B, "exif:HalftoneLPIUnit" },
{ 0x500C, "exif:HalftoneDegree" },
{ 0x500D, "exif:HalftoneShape" },
{ 0x500E, "exif:HalftoneMisc" },
{ 0x500F, "exif:HalftoneScreen" },
{ 0x5010, "exif:JPEGQuality" },
{ 0x5011, "exif:GridSize" },
{ 0x5012, "exif:ThumbnailFormat" },
{ 0x5013, "exif:ThumbnailWidth" },
{ 0x5014, "exif:ThumbnailHeight" },
{ 0x5015, "exif:ThumbnailColorDepth" },
{ 0x5016, "exif:ThumbnailPlanes" },
{ 0x5017, "exif:ThumbnailRawBytes" },
{ 0x5018, "exif:ThumbnailSize" },
{ 0x5019, "exif:ThumbnailCompressedSize" },
{ 0x501a, "exif:ColorTransferFunction" },
{ 0x501b, "exif:ThumbnailData" },
{ 0x5020, "exif:ThumbnailImageWidth" },
{ 0x5021, "exif:ThumbnailImageHeight" },
{ 0x5022, "exif:ThumbnailBitsPerSample" },
{ 0x5023, "exif:ThumbnailCompression" },
{ 0x5024, "exif:ThumbnailPhotometricInterp" },
{ 0x5025, "exif:ThumbnailImageDescription" },
{ 0x5026, "exif:ThumbnailEquipMake" },
{ 0x5027, "exif:ThumbnailEquipModel" },
{ 0x5028, "exif:ThumbnailStripOffsets" },
{ 0x5029, "exif:ThumbnailOrientation" },
{ 0x502a, "exif:ThumbnailSamplesPerPixel" },
{ 0x502b, "exif:ThumbnailRowsPerStrip" },
{ 0x502c, "exif:ThumbnailStripBytesCount" },
{ 0x502d, "exif:ThumbnailResolutionX" },
{ 0x502e, "exif:ThumbnailResolutionY" },
{ 0x502f, "exif:ThumbnailPlanarConfig" },
{ 0x5030, "exif:ThumbnailResolutionUnit" },
{ 0x5031, "exif:ThumbnailTransferFunction" },
{ 0x5032, "exif:ThumbnailSoftwareUsed" },
{ 0x5033, "exif:ThumbnailDateTime" },
{ 0x5034, "exif:ThumbnailArtist" },
{ 0x5035, "exif:ThumbnailWhitePoint" },
{ 0x5036, "exif:ThumbnailPrimaryChromaticities" },
{ 0x5037, "exif:ThumbnailYCbCrCoefficients" },
{ 0x5038, "exif:ThumbnailYCbCrSubsampling" },
{ 0x5039, "exif:ThumbnailYCbCrPositioning" },
{ 0x503A, "exif:ThumbnailRefBlackWhite" },
{ 0x503B, "exif:ThumbnailCopyRight" },
{ 0x5090, "exif:LuminanceTable" },
{ 0x5091, "exif:ChrominanceTable" },
{ 0x5100, "exif:FrameDelay" },
{ 0x5101, "exif:LoopCount" },
{ 0x5110, "exif:PixelUnit" },
{ 0x5111, "exif:PixelPerUnitX" },
{ 0x5112, "exif:PixelPerUnitY" },
{ 0x5113, "exif:PaletteHistogram" },
{ 0x1000, "exif:RelatedImageFileFormat" },
{ 0x1001, "exif:RelatedImageLength" },
{ 0x1002, "exif:RelatedImageWidth" },
{ 0x800d, "exif:ImageID" },
{ 0x80e3, "exif:Matteing" },
{ 0x80e4, "exif:DataType" },
{ 0x80e5, "exif:ImageDepth" },
{ 0x80e6, "exif:TileDepth" },
{ 0x828d, "exif:CFARepeatPatternDim" },
{ 0x828e, "exif:CFAPattern2" },
{ 0x828f, "exif:BatteryLevel" },
{ 0x8298, "exif:Copyright" },
{ 0x829a, "exif:ExposureTime" },
{ 0x829d, "exif:FNumber" },
{ 0x83bb, "exif:IPTC/NAA" },
{ 0x84e3, "exif:IT8RasterPadding" },
{ 0x84e5, "exif:IT8ColorTable" },
{ 0x8649, "exif:ImageResourceInformation" },
{ 0x8769, "exif:ExifOffset" },
{ 0x8773, "exif:InterColorProfile" },
{ 0x8822, "exif:ExposureProgram" },
{ 0x8824, "exif:SpectralSensitivity" },
{ 0x8825, "exif:GPSInfo" },
{ 0x8827, "exif:ISOSpeedRatings" },
{ 0x8828, "exif:OECF" },
{ 0x8829, "exif:Interlace" },
{ 0x882a, "exif:TimeZoneOffset" },
{ 0x882b, "exif:SelfTimerMode" },
{ 0x9000, "exif:ExifVersion" },
{ 0x9003, "exif:DateTimeOriginal" },
{ 0x9004, "exif:DateTimeDigitized" },
{ 0x9101, "exif:ComponentsConfiguration" },
{ 0x9102, "exif:CompressedBitsPerPixel" },
{ 0x9201, "exif:ShutterSpeedValue" },
{ 0x9202, "exif:ApertureValue" },
{ 0x9203, "exif:BrightnessValue" },
{ 0x9204, "exif:ExposureBiasValue" },
{ 0x9205, "exif:MaxApertureValue" },
{ 0x9206, "exif:SubjectDistance" },
{ 0x9207, "exif:MeteringMode" },
{ 0x9208, "exif:LightSource" },
{ 0x9209, "exif:Flash" },
{ 0x920a, "exif:FocalLength" },
{ 0x920b, "exif:FlashEnergy" },
{ 0x920c, "exif:SpatialFrequencyResponse" },
{ 0x920d, "exif:Noise" },
{ 0x9211, "exif:ImageNumber" },
{ 0x9212, "exif:SecurityClassification" },
{ 0x9213, "exif:ImageHistory" },
{ 0x9214, "exif:SubjectArea" },
{ 0x9215, "exif:ExposureIndex" },
{ 0x9216, "exif:TIFF-EPStandardID" },
{ 0x927c, "exif:MakerNote" },
{ 0x9C9b, "exif:WinXP-Title" },
{ 0x9C9c, "exif:WinXP-Comments" },
{ 0x9C9d, "exif:WinXP-Author" },
{ 0x9C9e, "exif:WinXP-Keywords" },
{ 0x9C9f, "exif:WinXP-Subject" },
{ 0x9286, "exif:UserComment" },
{ 0x9290, "exif:SubSecTime" },
{ 0x9291, "exif:SubSecTimeOriginal" },
{ 0x9292, "exif:SubSecTimeDigitized" },
{ 0xa000, "exif:FlashPixVersion" },
{ 0xa001, "exif:ColorSpace" },
{ 0xa002, "exif:ExifImageWidth" },
{ 0xa003, "exif:ExifImageLength" },
{ 0xa004, "exif:RelatedSoundFile" },
{ 0xa005, "exif:InteroperabilityOffset" },
{ 0xa20b, "exif:FlashEnergy" },
{ 0xa20c, "exif:SpatialFrequencyResponse" },
{ 0xa20d, "exif:Noise" },
{ 0xa20e, "exif:FocalPlaneXResolution" },
{ 0xa20f, "exif:FocalPlaneYResolution" },
{ 0xa210, "exif:FocalPlaneResolutionUnit" },
{ 0xa214, "exif:SubjectLocation" },
{ 0xa215, "exif:ExposureIndex" },
{ 0xa216, "exif:TIFF/EPStandardID" },
{ 0xa217, "exif:SensingMethod" },
{ 0xa300, "exif:FileSource" },
{ 0xa301, "exif:SceneType" },
{ 0xa302, "exif:CFAPattern" },
{ 0xa401, "exif:CustomRendered" },
{ 0xa402, "exif:ExposureMode" },
{ 0xa403, "exif:WhiteBalance" },
{ 0xa404, "exif:DigitalZoomRatio" },
{ 0xa405, "exif:FocalLengthIn35mmFilm" },
{ 0xa406, "exif:SceneCaptureType" },
{ 0xa407, "exif:GainControl" },
{ 0xa408, "exif:Contrast" },
{ 0xa409, "exif:Saturation" },
{ 0xa40a, "exif:Sharpness" },
{ 0xa40b, "exif:DeviceSettingDescription" },
{ 0xa40c, "exif:SubjectDistanceRange" },
{ 0xa420, "exif:ImageUniqueID" },
{ 0xc4a5, "exif:PrintImageMatching" },
{ 0xa500, "exif:Gamma" },
{ 0xc640, "exif:CR2Slice" },
{ 0x10000, "exif:GPSVersionID" },
{ 0x10001, "exif:GPSLatitudeRef" },
{ 0x10002, "exif:GPSLatitude" },
{ 0x10003, "exif:GPSLongitudeRef" },
{ 0x10004, "exif:GPSLongitude" },
{ 0x10005, "exif:GPSAltitudeRef" },
{ 0x10006, "exif:GPSAltitude" },
{ 0x10007, "exif:GPSTimeStamp" },
{ 0x10008, "exif:GPSSatellites" },
{ 0x10009, "exif:GPSStatus" },
{ 0x1000a, "exif:GPSMeasureMode" },
{ 0x1000b, "exif:GPSDop" },
{ 0x1000c, "exif:GPSSpeedRef" },
{ 0x1000d, "exif:GPSSpeed" },
{ 0x1000e, "exif:GPSTrackRef" },
{ 0x1000f, "exif:GPSTrack" },
{ 0x10010, "exif:GPSImgDirectionRef" },
{ 0x10011, "exif:GPSImgDirection" },
{ 0x10012, "exif:GPSMapDatum" },
{ 0x10013, "exif:GPSDestLatitudeRef" },
{ 0x10014, "exif:GPSDestLatitude" },
{ 0x10015, "exif:GPSDestLongitudeRef" },
{ 0x10016, "exif:GPSDestLongitude" },
{ 0x10017, "exif:GPSDestBearingRef" },
{ 0x10018, "exif:GPSDestBearing" },
{ 0x10019, "exif:GPSDestDistanceRef" },
{ 0x1001a, "exif:GPSDestDistance" },
{ 0x1001b, "exif:GPSProcessingMethod" },
{ 0x1001c, "exif:GPSAreaInformation" },
{ 0x1001d, "exif:GPSDateStamp" },
{ 0x1001e, "exif:GPSDifferential" },
{ 0x00000, (const char *) NULL }
};
const StringInfo
*profile;
const unsigned char
*directory,
*exif;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
MagickBooleanType
status;
register ssize_t
i;
size_t
entry,
length,
number_entries,
tag,
tag_value;
SplayTreeInfo
*exif_resources;
ssize_t
all,
id,
level,
offset,
tag_offset;
static int
tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
/*
If EXIF data exists, then try to parse the request for a tag.
*/
profile=GetImageProfile(image,"exif");
if (profile == (const StringInfo *) NULL)
return(MagickFalse);
if ((property == (const char *) NULL) || (*property == '\0'))
return(MagickFalse);
while (isspace((int) ((unsigned char) *property)) != 0)
property++;
if (strlen(property) <= 5)
return(MagickFalse);
all=0;
tag=(~0UL);
switch (*(property+5))
{
case '*':
{
/*
Caller has asked for all the tags in the EXIF data.
*/
tag=0;
all=1; /* return the data in description=value format */
break;
}
case '!':
{
tag=0;
all=2; /* return the data in tagid=value format */
break;
}
case '#':
case '@':
{
int
c;
size_t
n;
/*
Check for a hex based tag specification first.
*/
tag=(*(property+5) == '@') ? 1UL : 0UL;
property+=6;
n=strlen(property);
if (n != 4)
return(MagickFalse);
/*
Parse tag specification as a hex number.
*/
n/=4;
do
{
for (i=(ssize_t) n-1L; i >= 0; i--)
{
c=(*property++);
tag<<=4;
if ((c >= '0') && (c <= '9'))
tag|=(c-'0');
else
if ((c >= 'A') && (c <= 'F'))
tag|=(c-('A'-10));
else
if ((c >= 'a') && (c <= 'f'))
tag|=(c-('a'-10));
else
return(MagickFalse);
}
} while (*property != '\0');
break;
}
default:
{
/*
Try to match the text with a tag name instead.
*/
for (i=0; ; i++)
{
if (EXIFTag[i].tag == 0)
break;
if (LocaleCompare(EXIFTag[i].description,property) == 0)
{
tag=(size_t) EXIFTag[i].tag;
break;
}
}
break;
}
}
if (tag == (~0UL))
return(MagickFalse);
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadPropertyByte(&exif,&length) != 0x45)
continue;
if (ReadPropertyByte(&exif,&length) != 0x78)
continue;
if (ReadPropertyByte(&exif,&length) != 0x69)
continue;
if (ReadPropertyByte(&exif,&length) != 0x66)
continue;
if (ReadPropertyByte(&exif,&length) != 0x00)
continue;
if (ReadPropertyByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif);
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadPropertySignedLong(endian,exif+4);
if ((offset < 0) || (size_t) offset >= length)
return(MagickFalse);
/*
Set the pointer to the first IFD and follow it were it leads.
*/
status=MagickFalse;
directory=exif+offset;
level=0;
entry=0;
tag_offset=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
/*
If there is anything on the stack then pop it off.
*/
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
tag_offset=directory_stack[level].offset;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
register unsigned char
*p,
*q;
size_t
format;
ssize_t
number_bytes,
components;
q=(unsigned char *) (directory+(12*entry)+2);
if (q > (exif+length-12))
break; /* corrupt EXIF */
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset;
format=(size_t) ReadPropertyUnsignedShort(endian,q+2);
if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes)))
break;
components=(ssize_t) ReadPropertySignedLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*tag_bytes[format];
if (number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
ssize_t
offset;
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadPropertySignedLong(endian,q+8);
if ((offset < 0) || (size_t) offset >= length)
continue;
if ((ssize_t) (offset+number_bytes) < offset)
continue; /* prevent overflow */
if ((size_t) (offset+number_bytes) > length)
continue;
p=(unsigned char *) (exif+offset);
}
if ((all != 0) || (tag == (size_t) tag_value))
{
char
buffer[MagickPathExtent],
*value;
value=(char *) NULL;
*buffer='\0';
switch (format)
{
case EXIF_FMT_BYTE:
case EXIF_FMT_UNDEFINED:
{
EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1));
break;
}
case EXIF_FMT_SBYTE:
{
EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1));
break;
}
case EXIF_FMT_SSHORT:
{
EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1));
break;
}
case EXIF_FMT_USHORT:
{
EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1));
break;
}
case EXIF_FMT_ULONG:
{
EXIFMultipleValues(4,"%.20g",(double)
ReadPropertyUnsignedLong(endian,p1));
break;
}
case EXIF_FMT_SLONG:
{
EXIFMultipleValues(4,"%.20g",(double)
ReadPropertySignedLong(endian,p1));
break;
}
case EXIF_FMT_URATIONAL:
{
EXIFMultipleFractions(8,"%.20g/%.20g",(double)
ReadPropertyUnsignedLong(endian,p1),(double)
ReadPropertyUnsignedLong(endian,p1+4));
break;
}
case EXIF_FMT_SRATIONAL:
{
EXIFMultipleFractions(8,"%.20g/%.20g",(double)
ReadPropertySignedLong(endian,p1),(double)
ReadPropertySignedLong(endian,p1+4));
break;
}
case EXIF_FMT_SINGLE:
{
EXIFMultipleValues(4,"%f",(double) *(float *) p1);
break;
}
case EXIF_FMT_DOUBLE:
{
EXIFMultipleValues(8,"%f",*(double *) p1);
break;
}
default:
case EXIF_FMT_STRING:
{
value=(char *) NULL;
if (~((size_t) number_bytes) >= 1)
value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL,
sizeof(*value));
if (value != (char *) NULL)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_bytes; i++)
{
value[i]='.';
if ((isprint((int) p[i]) != 0) || (p[i] == '\0'))
value[i]=(char) p[i];
}
value[i]='\0';
}
break;
}
}
if (value != (char *) NULL)
{
char
*key;
register const char
*p;
key=AcquireString(property);
switch (all)
{
case 1:
{
const char
*description;
register ssize_t
i;
description="unknown";
for (i=0; ; i++)
{
if (EXIFTag[i].tag == 0)
break;
if (EXIFTag[i].tag == tag_value)
{
description=EXIFTag[i].description;
break;
}
}
(void) FormatLocaleString(key,MagickPathExtent,"%s",
description);
if (level == 2)
(void) SubstituteString(&key,"exif:","exif:thumbnail:");
break;
}
case 2:
{
if (tag_value < 0x10000)
(void) FormatLocaleString(key,MagickPathExtent,"#%04lx",
(unsigned long) tag_value);
else
if (tag_value < 0x20000)
(void) FormatLocaleString(key,MagickPathExtent,"@%04lx",
(unsigned long) (tag_value & 0xffff));
else
(void) FormatLocaleString(key,MagickPathExtent,"unknown");
break;
}
default:
{
if (level == 2)
(void) SubstituteString(&key,"exif:","exif:thumbnail:");
}
}
p=(const char *) NULL;
if (image->properties != (void *) NULL)
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,key);
if (p == (const char *) NULL)
(void) SetImageProperty((Image *) image,key,value,exception);
value=DestroyString(value);
key=DestroyString(key);
status=MagickTrue;
}
}
if ((tag_value == TAG_EXIF_OFFSET) ||
(tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET))
{
ssize_t
offset;
offset=(ssize_t) ReadPropertySignedLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
ssize_t
tag_offset1;
tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 :
0);
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
directory_stack[level].offset=tag_offset;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].offset=tag_offset1;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadPropertySignedLong(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;
directory_stack[level].offset=tag_offset1;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(status);
}
static MagickBooleanType GetICCProperty(const Image *image,const char *property,
ExceptionInfo *exception)
{
const StringInfo
*profile;
magick_unreferenced(property);
profile=GetImageProfile(image,"icc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"icm");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
if (GetStringInfoLength(profile) < 128)
return(MagickFalse); /* minimum ICC profile length */
#if defined(MAGICKCORE_LCMS_DELEGATE)
{
cmsHPROFILE
icc_profile;
icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile),
(cmsUInt32Number) GetStringInfoLength(profile));
if (icc_profile != (cmsHPROFILE *) NULL)
{
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
const char
*name;
name=cmsTakeProductName(icc_profile);
if (name != (const char *) NULL)
(void) SetImageProperty((Image *) image,"icc:name",name,exception);
#else
char
info[MagickPathExtent];
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:description",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:manufacturer",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en","US",info,
MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:model",info,exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright,"en","US",
info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:copyright",info,exception);
#endif
(void) cmsCloseProfile(icc_profile);
}
}
#endif
return(MagickTrue);
}
static MagickBooleanType SkipXMPValue(const char *value)
{
if (value == (const char*) NULL)
return(MagickTrue);
while (*value != '\0')
{
if (isspace((int) ((unsigned char) *value)) == 0)
return(MagickFalse);
value++;
}
return(MagickTrue);
}
static MagickBooleanType GetXMPProperty(const Image *image,const char *property)
{
char
*xmp_profile;
const char
*content;
const StringInfo
*profile;
ExceptionInfo
*exception;
MagickBooleanType
status;
register const char
*p;
XMLTreeInfo
*child,
*description,
*node,
*rdf,
*xmp;
profile=GetImageProfile(image,"xmp");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
if ((property == (const char *) NULL) || (*property == '\0'))
return(MagickFalse);
xmp_profile=StringInfoToString(profile);
if (xmp_profile == (char *) NULL)
return(MagickFalse);
for (p=xmp_profile; *p != '\0'; p++)
if ((*p == '<') && (*(p+1) == 'x'))
break;
exception=AcquireExceptionInfo();
xmp=NewXMLTree((char *) p,exception);
xmp_profile=DestroyString(xmp_profile);
exception=DestroyExceptionInfo(exception);
if (xmp == (XMLTreeInfo *) NULL)
return(MagickFalse);
status=MagickFalse;
rdf=GetXMLTreeChild(xmp,"rdf:RDF");
if (rdf != (XMLTreeInfo *) NULL)
{
if (image->properties == (void *) NULL)
((Image *) image)->properties=NewSplayTree(CompareSplayTreeString,
RelinquishMagickMemory,RelinquishMagickMemory);
description=GetXMLTreeChild(rdf,"rdf:Description");
while (description != (XMLTreeInfo *) NULL)
{
node=GetXMLTreeChild(description,(const char *) NULL);
while (node != (XMLTreeInfo *) NULL)
{
child=GetXMLTreeChild(node,(const char *) NULL);
content=GetXMLTreeContent(node);
if ((child == (XMLTreeInfo *) NULL) &&
(SkipXMPValue(content) == MagickFalse))
(void) AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(GetXMLTreeTag(node)),ConstantString(content));
while (child != (XMLTreeInfo *) NULL)
{
content=GetXMLTreeContent(child);
if (SkipXMPValue(content) == MagickFalse)
(void) AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(GetXMLTreeTag(child)),ConstantString(content));
child=GetXMLTreeSibling(child);
}
node=GetXMLTreeSibling(node);
}
description=GetNextXMLTreeTag(description);
}
}
xmp=DestroyXMLTree(xmp);
return(status);
}
static char *TracePSClippath(const unsigned char *blob,size_t length)
{
char
*path,
*message;
MagickBooleanType
in_subpath;
PointInfo
first[3],
last[3],
point[3];
register ssize_t
i,
x;
ssize_t
knot_count,
selector,
y;
path=AcquireString((char *) NULL);
if (path == (char *) NULL)
return((char *) NULL);
message=AcquireString((char *) NULL);
(void) FormatLocaleString(message,MagickPathExtent,"/ClipImage\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,"{\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /c {curveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /l {lineto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /m {moveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /v {currentpoint 6 2 roll curveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /y {2 copy curveto} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,
" /z {closepath} bind def\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent," newpath\n");
(void) ConcatenateString(&path,message);
/*
The clipping path format is defined in "Adobe Photoshop File Formats
Specification" version 6.0 downloadable from adobe.com.
*/
(void) ResetMagickMemory(point,0,sizeof(point));
(void) ResetMagickMemory(first,0,sizeof(first));
(void) ResetMagickMemory(last,0,sizeof(last));
knot_count=0;
in_subpath=MagickFalse;
while (length > 0)
{
selector=(ssize_t) ReadPropertyMSBShort(&blob,&length);
switch (selector)
{
case 0:
case 3:
{
if (knot_count != 0)
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Expected subpath length record.
*/
knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length);
blob+=22;
length-=MagickMin(22,(ssize_t) length);
break;
}
case 1:
case 2:
case 4:
case 5:
{
if (knot_count == 0)
{
/*
Unexpected subpath knot
*/
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Add sub-path knot
*/
for (i=0; i < 3; i++)
{
size_t
xx,
yy;
yy=(size_t) ReadPropertyMSBLong(&blob,&length);
xx=(size_t) ReadPropertyMSBLong(&blob,&length);
x=(ssize_t) xx;
if (xx > 2147483647)
x=(ssize_t) xx-4294967295U-1;
y=(ssize_t) yy;
if (yy > 2147483647)
y=(ssize_t) yy-4294967295U-1;
point[i].x=(double) x/4096/4096;
point[i].y=1.0-(double) y/4096/4096;
}
if (in_subpath == MagickFalse)
{
(void) FormatLocaleString(message,MagickPathExtent," %g %g m\n",
point[1].x,point[1].y);
for (i=0; i < 3; i++)
{
first[i]=point[i];
last[i]=point[i];
}
}
else
{
/*
Handle special cases when Bezier curves are used to describe
corners and straight lines.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g l\n",point[1].x,point[1].y);
else
if ((last[1].x == last[2].x) && (last[1].y == last[2].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g v\n",point[0].x,point[0].y,
point[1].x,point[1].y);
else
if ((point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g y\n",last[2].x,last[2].y,
point[1].x,point[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g %g %g c\n",last[2].x,
last[2].y,point[0].x,point[0].y,point[1].x,point[1].y);
for (i=0; i < 3; i++)
last[i]=point[i];
}
(void) ConcatenateString(&path,message);
in_subpath=MagickTrue;
knot_count--;
/*
Close the subpath if there are no more knots.
*/
if (knot_count == 0)
{
/*
Same special handling as above except we compare to the
first point in the path and close the path.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g l z\n",first[1].x,first[1].y);
else
if ((last[1].x == last[2].x) && (last[1].y == last[2].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g v z\n",first[0].x,first[0].y,
first[1].x,first[1].y);
else
if ((first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g y z\n",last[2].x,last[2].y,
first[1].x,first[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
" %g %g %g %g %g %g c z\n",last[2].x,
last[2].y,first[0].x,first[0].y,first[1].x,first[1].y);
(void) ConcatenateString(&path,message);
in_subpath=MagickFalse;
}
break;
}
case 6:
case 7:
case 8:
default:
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
}
}
/*
Returns an empty PS path if the path has no knots.
*/
(void) FormatLocaleString(message,MagickPathExtent," eoclip\n");
(void) ConcatenateString(&path,message);
(void) FormatLocaleString(message,MagickPathExtent,"} bind def");
(void) ConcatenateString(&path,message);
message=DestroyString(message);
return(path);
}
static char *TraceSVGClippath(const unsigned char *blob,size_t length,
const size_t columns,const size_t rows)
{
char
*path,
*message;
MagickBooleanType
in_subpath;
PointInfo
first[3],
last[3],
point[3];
register ssize_t
i;
ssize_t
knot_count,
selector,
x,
y;
path=AcquireString((char *) NULL);
if (path == (char *) NULL)
return((char *) NULL);
message=AcquireString((char *) NULL);
(void) FormatLocaleString(message,MagickPathExtent,(
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
"<svg xmlns=\"http://www.w3.org/2000/svg\""
" width=\"%.20g\" height=\"%.20g\">\n"
"<g>\n"
"<path fill-rule=\"evenodd\" style=\"fill:#00000000;stroke:#00000000;"
"stroke-width:0;stroke-antialiasing:false\" d=\"\n"),(double) columns,
(double) rows);
(void) ConcatenateString(&path,message);
(void) ResetMagickMemory(point,0,sizeof(point));
(void) ResetMagickMemory(first,0,sizeof(first));
(void) ResetMagickMemory(last,0,sizeof(last));
knot_count=0;
in_subpath=MagickFalse;
while (length != 0)
{
selector=(ssize_t) ReadPropertyMSBShort(&blob,&length);
switch (selector)
{
case 0:
case 3:
{
if (knot_count != 0)
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Expected subpath length record.
*/
knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length);
blob+=22;
length-=MagickMin(22,(ssize_t) length);
break;
}
case 1:
case 2:
case 4:
case 5:
{
if (knot_count == 0)
{
/*
Unexpected subpath knot.
*/
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Add sub-path knot
*/
for (i=0; i < 3; i++)
{
unsigned int
xx,
yy;
yy=(unsigned int) ReadPropertyMSBLong(&blob,&length);
xx=(unsigned int) ReadPropertyMSBLong(&blob,&length);
x=(ssize_t) xx;
if (xx > 2147483647)
x=(ssize_t) xx-4294967295U-1;
y=(ssize_t) yy;
if (yy > 2147483647)
y=(ssize_t) yy-4294967295U-1;
point[i].x=(double) x*columns/4096/4096;
point[i].y=(double) y*rows/4096/4096;
}
if (in_subpath == MagickFalse)
{
(void) FormatLocaleString(message,MagickPathExtent,"M %g %g\n",
point[1].x,point[1].y);
for (i=0; i < 3; i++)
{
first[i]=point[i];
last[i]=point[i];
}
}
else
{
/*
Handle special cases when Bezier curves are used to describe
corners and straight lines.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
"L %g %g\n",point[1].x,point[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
"C %g %g %g %g %g %g\n",last[2].x,
last[2].y,point[0].x,point[0].y,point[1].x,point[1].y);
for (i=0; i < 3; i++)
last[i]=point[i];
}
(void) ConcatenateString(&path,message);
in_subpath=MagickTrue;
knot_count--;
/*
Close the subpath if there are no more knots.
*/
if (knot_count == 0)
{
/*
Same special handling as above except we compare to the
first point in the path and close the path.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
"L %g %g Z\n",first[1].x,first[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
"C %g %g %g %g %g %g Z\n",last[2].x,
last[2].y,first[0].x,first[0].y,first[1].x,first[1].y);
(void) ConcatenateString(&path,message);
in_subpath=MagickFalse;
}
break;
}
case 6:
case 7:
case 8:
default:
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
}
}
/*
Return an empty SVG image if the path does not have knots.
*/
(void) ConcatenateString(&path,"\"/>\n</g>\n</svg>\n");
message=DestroyString(message);
return(path);
}
MagickExport const char *GetImageProperty(const Image *image,
const char *property,ExceptionInfo *exception)
{
register const char
*p;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
p=(const char *) NULL;
if (image->properties != (void *) NULL)
{
if (property == (const char *) NULL)
{
ResetSplayTreeIterator((SplayTreeInfo *) image->properties);
p=(const char *) GetNextValueInSplayTree((SplayTreeInfo *)
image->properties);
return(p);
}
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,property);
if (p != (const char *) NULL)
return(p);
}
if ((property == (const char *) NULL) ||
(strchr(property,':') == (char *) NULL))
return(p);
switch (*property)
{
case '8':
{
if (LocaleNCompare("8bim:",property,5) == 0)
{
(void) Get8BIMProperty(image,property,exception);
break;
}
break;
}
case 'E':
case 'e':
{
if (LocaleNCompare("exif:",property,5) == 0)
{
(void) GetEXIFProperty(image,property,exception);
break;
}
break;
}
case 'I':
case 'i':
{
if ((LocaleNCompare("icc:",property,4) == 0) ||
(LocaleNCompare("icm:",property,4) == 0))
{
(void) GetICCProperty(image,property,exception);
break;
}
if (LocaleNCompare("iptc:",property,5) == 0)
{
(void) GetIPTCProperty(image,property,exception);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleNCompare("xmp:",property,4) == 0)
{
(void) GetXMPProperty(image,property);
break;
}
break;
}
default:
break;
}
if (image->properties != (void *) NULL)
{
p=(const char *) GetValueFromSplayTree((SplayTreeInfo *)
image->properties,property);
return(p);
}
return((const char *) NULL);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t M a g i c k P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetMagickProperty() gets attributes or calculated values that is associated
% with a fixed known property name, or single letter property. It may be
% called if no image is defined (IMv7), in which case only global image_info
% values are available:
%
% \n newline
% \r carriage return
% < less-than character.
% > greater-than character.
% & ampersand character.
% %% a percent sign
% %b file size of image read in
% %c comment meta-data property
% %d directory component of path
% %e filename extension or suffix
% %f filename (including suffix)
% %g layer canvas page geometry (equivalent to "%Wx%H%X%Y")
% %h current image height in pixels
% %i image filename (note: becomes output filename for "info:")
% %k CALCULATED: number of unique colors
% %l label meta-data property
% %m image file format (file magic)
% %n number of images in current image sequence
% %o output filename (used for delegates)
% %p index of image in current image list
% %q quantum depth (compile-time constant)
% %r image class and colorspace
% %s scene number (from input unless re-assigned)
% %t filename without directory or extension (suffix)
% %u unique temporary filename (used for delegates)
% %w current width in pixels
% %x x resolution (density)
% %y y resolution (density)
% %z image depth (as read in unless modified, image save depth)
% %A image transparency channel enabled (true/false)
% %C image compression type
% %D image GIF dispose method
% %G original image size (%wx%h; before any resizes)
% %H page (canvas) height
% %M Magick filename (original file exactly as given, including read mods)
% %O page (canvas) offset ( = %X%Y )
% %P page (canvas) size ( = %Wx%H )
% %Q image compression quality ( 0 = default )
% %S ?? scenes ??
% %T image time delay (in centi-seconds)
% %U image resolution units
% %W page (canvas) width
% %X page (canvas) x offset (including sign)
% %Y page (canvas) y offset (including sign)
% %Z unique filename (used for delegates)
% %@ CALCULATED: trim bounding box (without actually trimming)
% %# CALCULATED: 'signature' hash of image values
%
% This routine only handles specifically known properties. It does not
% handle special prefixed properties, profiles, or expressions. Nor does
% it return any free-form property strings.
%
% The returned string is stored in a structure somewhere, and should not be
% directly freed. If the string was generated (common) the string will be
% stored as as either as artifact or option 'get-property'. These may be
% deleted (cleaned up) when no longer required, but neither artifact or
% option is guranteed to exist.
%
% The format of the GetMagickProperty method is:
%
% const char *GetMagickProperty(ImageInfo *image_info,Image *image,
% const char *property,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info (optional)
%
% o image: the image (optional)
%
% o key: the key.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const char *GetMagickPropertyLetter(ImageInfo *image_info,
Image *image,const char letter,ExceptionInfo *exception)
{
#define WarnNoImageReturn(format,arg) \
if (image == (Image *) NULL ) { \
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \
"NoImageForProperty",format,arg); \
return((const char *) NULL); \
}
#define WarnNoImageInfoReturn(format,arg) \
if (image_info == (ImageInfo *) NULL ) { \
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \
"NoImageInfoForProperty",format,arg); \
return((const char *) NULL); \
}
char
value[MagickPathExtent]; /* formatted string to store as an artifact */
const char
*string; /* return a string already stored somewher */
if ((image != (Image *) NULL) && (image->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
else
if ((image_info != (ImageInfo *) NULL) &&
(image_info->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images");
*value='\0'; /* formatted string */
string=(char *) NULL; /* constant string reference */
/*
Get properities that are directly defined by images.
*/
switch (letter)
{
case 'b': /* image size read in - in bytes */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatMagickSize(image->extent,MagickFalse,"B",MagickPathExtent,
value);
if (image->extent == 0)
(void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",
MagickPathExtent,value);
break;
}
case 'c': /* image comment property - empty string by default */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=GetImageProperty(image,"comment",exception);
if ( string == (const char *) NULL )
string="";
break;
}
case 'd': /* Directory component of filename */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,HeadPath,value);
if (*value == '\0')
string="";
break;
}
case 'e': /* Filename extension (suffix) of image file */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,ExtensionPath,value);
if (*value == '\0')
string="";
break;
}
case 'f': /* Filename without directory component */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,TailPath,value);
if (*value == '\0')
string="";
break;
}
case 'g': /* Image geometry, canvas and offset %Wx%H+%X+%Y */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
break;
}
case 'h': /* Image height (current) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->rows != 0 ? image->rows : image->magick_rows));
break;
}
case 'i': /* Filename last used for an image (read or write) */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=image->filename;
break;
}
case 'k': /* Number of unique colors */
{
/*
FUTURE: ensure this does not generate the formatted comment!
*/
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetNumberColors(image,(FILE *) NULL,exception));
break;
}
case 'l': /* Image label property - empty string by default */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=GetImageProperty(image,"label",exception);
if (string == (const char *) NULL)
string="";
break;
}
case 'm': /* Image format (file magick) */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=image->magick;
break;
}
case 'n': /* Number of images in the list. */
{
if ( image != (Image *) NULL )
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageListLength(image));
else
string="0"; /* no images or scenes */
break;
}
case 'o': /* Output Filename - for delegate use only */
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->filename;
break;
case 'p': /* Image index in current image list */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageIndexInList(image));
break;
}
case 'q': /* Quantum depth of image in memory */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
MAGICKCORE_QUANTUM_DEPTH);
break;
}
case 'r': /* Image storage class, colorspace, and alpha enabled. */
{
ColorspaceType
colorspace;
WarnNoImageReturn("\"%%%c\"",letter);
colorspace=image->colorspace;
if (SetImageGray(image,exception) != MagickFalse)
colorspace=GRAYColorspace; /* FUTURE: this is IMv6 not IMv7 */
(void) FormatLocaleString(value,MagickPathExtent,"%s %s %s",
CommandOptionToMnemonic(MagickClassOptions,(ssize_t)
image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions,
(ssize_t) colorspace),image->alpha_trait != UndefinedPixelTrait ?
"Alpha" : "");
break;
}
case 's': /* Image scene number */
{
#if 0 /* this seems non-sensical -- simplifing */
if (image_info->number_scenes != 0)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image_info->scene);
else if (image != (Image *) NULL)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->scene);
else
string="0";
#else
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->scene);
#endif
break;
}
case 't': /* Base filename without directory or extention */
{
WarnNoImageReturn("\"%%%c\"",letter);
GetPathComponent(image->magick_filename,BasePath,value);
if (*value == '\0')
string="";
break;
}
case 'u': /* Unique filename */
{
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->unique;
break;
}
case 'w': /* Image width (current) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->columns != 0 ? image->columns : image->magick_columns));
break;
}
case 'x': /* Image horizontal resolution (with units) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",
fabs(image->resolution.x) > MagickEpsilon ? image->resolution.x : 72.0);
break;
}
case 'y': /* Image vertical resolution (with units) */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",
fabs(image->resolution.y) > MagickEpsilon ? image->resolution.y : 72.0);
break;
}
case 'z': /* Image depth as read in */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->depth);
break;
}
case 'A': /* Image alpha channel */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickPixelTraitOptions,(ssize_t)
image->alpha_trait);
break;
}
case 'C': /* Image compression method. */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickCompressOptions,(ssize_t)
image->compression);
break;
}
case 'D': /* Image dispose method. */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t)
image->dispose);
break;
}
case 'G': /* Image size as geometry = "%wx%h" */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g",(double)
image->magick_columns,(double) image->magick_rows);
break;
}
case 'H': /* layer canvas height */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->page.height);
break;
}
case 'M': /* Magick filename - filename given incl. coder & read mods */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=image->magick_filename;
break;
}
case 'O': /* layer canvas offset with sign = "+%X+%Y" */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%+ld%+ld",(long)
image->page.x,(long) image->page.y);
break;
}
case 'P': /* layer canvas page size = "%Wx%H" */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g",(double)
image->page.width,(double) image->page.height);
break;
}
case 'Q': /* image compression quality */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->quality == 0 ? 92 : image->quality));
break;
}
case 'S': /* Number of scenes in image list. */
{
WarnNoImageInfoReturn("\"%%%c\"",letter);
#if 0 /* What is this number? -- it makes no sense - simplifing */
if (image_info->number_scenes == 0)
string="2147483647";
else if ( image != (Image *) NULL )
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image_info->scene+image_info->number_scenes);
else
string="0";
#else
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image_info->number_scenes == 0 ? 2147483647 :
image_info->number_scenes));
#endif
break;
}
case 'T': /* image time delay for animations */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->delay);
break;
}
case 'U': /* Image resolution units. */
{
WarnNoImageReturn("\"%%%c\"",letter);
string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)
image->units);
break;
}
case 'W': /* layer canvas width */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->page.width);
break;
}
case 'X': /* layer canvas X offset */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double)
image->page.x);
break;
}
case 'Y': /* layer canvas Y offset */
{
WarnNoImageReturn("\"%%%c\"",letter);
(void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double)
image->page.y);
break;
}
case '%': /* percent escaped */
{
string="%";
break;
}
case '@': /* Trim bounding box, without actually Trimming! */
{
RectangleInfo
page;
WarnNoImageReturn("\"%%%c\"",letter);
page=GetImageBoundingBox(image,exception);
(void) FormatLocaleString(value,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) page.width,(double) page.height,
(double) page.x,(double)page.y);
break;
}
case '#':
{
/*
Image signature.
*/
WarnNoImageReturn("\"%%%c\"",letter);
(void) SignatureImage(image,exception);
string=GetImageProperty(image,"signature",exception);
break;
}
}
if (string != (char *) NULL)
return(string);
if (*value != '\0')
{
/*
Create a cloned copy of result.
*/
if (image != (Image *) NULL)
{
(void) SetImageArtifact(image,"get-property",value);
return(GetImageArtifact(image,"get-property"));
}
else
{
(void) SetImageOption(image_info,"get-property",value);
return(GetImageOption(image_info,"get-property"));
}
}
return((char *) NULL);
}
MagickExport const char *GetMagickProperty(ImageInfo *image_info,
Image *image,const char *property,ExceptionInfo *exception)
{
char
value[MagickPathExtent];
const char
*string;
assert(property[0] != '\0');
assert(image != (Image *) NULL || image_info != (ImageInfo *) NULL );
if (property[1] == '\0') /* single letter property request */
return(GetMagickPropertyLetter(image_info,image,*property,exception));
if ((image != (Image *) NULL) && (image->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
else
if ((image_info != (ImageInfo *) NULL) &&
(image_info->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images");
*value='\0'; /* formated string */
string=(char *) NULL; /* constant string reference */
switch (*property)
{
case 'b':
{
if (LocaleCompare("basename",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
GetPathComponent(image->magick_filename,BasePath,value);
if (*value == '\0')
string="";
break;
}
if (LocaleCompare("bit-depth",property) == 0)
{
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageDepth(image,exception));
break;
}
break;
}
case 'c':
{
if (LocaleCompare("channels",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
/* FUTURE: return actual image channels */
(void) FormatLocaleString(value,MagickPathExtent,"%s",
CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t)
image->colorspace));
LocaleLower(value);
if( image->alpha_trait != UndefinedPixelTrait )
(void) ConcatenateMagickString(value,"a",MagickPathExtent);
break;
}
if (LocaleCompare("colorspace",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
/* FUTURE: return actual colorspace - no 'gray' stuff */
string=CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t)
image->colorspace);
break;
}
if (LocaleCompare("compose",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickComposeOptions,(ssize_t)
image->compose);
break;
}
if (LocaleCompare("copyright",property) == 0)
{
(void) CopyMagickString(value,GetMagickCopyright(),MagickPathExtent);
break;
}
break;
}
case 'd':
{
if (LocaleCompare("depth",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->depth);
break;
}
if (LocaleCompare("directory",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
GetPathComponent(image->magick_filename,HeadPath,value);
if (*value == '\0')
string="";
break;
}
break;
}
case 'e':
{
if (LocaleCompare("entropy",property) == 0)
{
double
entropy;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageEntropy(image,&entropy,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),entropy);
break;
}
if (LocaleCompare("extension",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
GetPathComponent(image->magick_filename,ExtensionPath,value);
if (*value == '\0')
string="";
break;
}
break;
}
case 'g':
{
if (LocaleCompare("gamma",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),image->gamma);
break;
}
break;
}
case 'h':
{
if (LocaleCompare("height",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",
image->magick_rows != 0 ? (double) image->magick_rows : 256.0);
break;
}
break;
}
case 'i':
{
if (LocaleCompare("input",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=image->filename;
break;
}
break;
}
case 'k':
{
if (LocaleCompare("kurtosis",property) == 0)
{
double
kurtosis,
skewness;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),kurtosis);
break;
}
break;
}
case 'm':
{
if (LocaleCompare("magick",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=image->magick;
break;
}
if ((LocaleCompare("maxima",property) == 0) ||
(LocaleCompare("max",property) == 0))
{
double
maximum,
minimum;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageRange(image,&minimum,&maximum,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),maximum);
break;
}
if (LocaleCompare("mean",property) == 0)
{
double
mean,
standard_deviation;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),mean);
break;
}
if ((LocaleCompare("minima",property) == 0) ||
(LocaleCompare("min",property) == 0))
{
double
maximum,
minimum;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageRange(image,&minimum,&maximum,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),minimum);
break;
}
break;
}
case 'o':
{
if (LocaleCompare("opaque",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t)
IsImageOpaque(image,exception));
break;
}
if (LocaleCompare("orientation",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickOrientationOptions,(ssize_t)
image->orientation);
break;
}
if (LocaleCompare("output",property) == 0)
{
WarnNoImageInfoReturn("\"%%[%s]\"",property);
(void) CopyMagickString(value,image_info->filename,MagickPathExtent);
break;
}
break;
}
case 'p':
{
#if defined(MAGICKCORE_LCMS_DELEGATE)
if (LocaleCompare("profile:icc",property) == 0 ||
LocaleCompare("profile:icm",property) == 0)
{
#if !defined(LCMS_VERSION) || (LCMS_VERSION < 2000)
#define cmsUInt32Number DWORD
#endif
const StringInfo
*profile;
cmsHPROFILE
icc_profile;
profile=GetImageProfile(image,property+8);
if (profile == (StringInfo *) NULL)
break;
icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile),
(cmsUInt32Number) GetStringInfoLength(profile));
if (icc_profile != (cmsHPROFILE *) NULL)
{
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
string=cmsTakeProductName(icc_profile);
#else
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,
"en","US",value,MagickPathExtent);
#endif
(void) cmsCloseProfile(icc_profile);
}
}
#endif
if (LocaleCompare("profiles",property) == 0)
{
const char
*name;
ResetImageProfileIterator(image);
name=GetNextImageProfile(image);
if (name != (char *) NULL)
{
(void) CopyMagickString(value,name,MagickPathExtent);
name=GetNextImageProfile(image);
while (name != (char *) NULL)
{
ConcatenateMagickString(value,",",MagickPathExtent);
ConcatenateMagickString(value,name,MagickPathExtent);
name=GetNextImageProfile(image);
}
}
break;
}
break;
}
case 'r':
{
if (LocaleCompare("resolution.x",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.x);
break;
}
if (LocaleCompare("resolution.y",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.y);
break;
}
break;
}
case 's':
{
if (LocaleCompare("scene",property) == 0)
{
WarnNoImageInfoReturn("\"%%[%s]\"",property);
if (image_info->number_scenes != 0)
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image_info->scene);
else {
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
image->scene);
}
break;
}
if (LocaleCompare("scenes",property) == 0)
{
/* FUTURE: equivelent to %n? */
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
GetImageListLength(image));
break;
}
if (LocaleCompare("size",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",
MagickPathExtent,value);
break;
}
if (LocaleCompare("skewness",property) == 0)
{
double
kurtosis,
skewness;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageKurtosis(image,&kurtosis,&skewness,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),skewness);
break;
}
if (LocaleCompare("standard-deviation",property) == 0)
{
double
mean,
standard_deviation;
WarnNoImageReturn("\"%%[%s]\"",property);
(void) GetImageMean(image,&mean,&standard_deviation,exception);
(void) FormatLocaleString(value,MagickPathExtent,"%.*g",
GetMagickPrecision(),standard_deviation);
break;
}
break;
}
case 't':
{
if (LocaleCompare("type",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickTypeOptions,(ssize_t)
IdentifyImageType(image,exception));
break;
}
break;
}
case 'u':
{
if (LocaleCompare("unique",property) == 0)
{
WarnNoImageInfoReturn("\"%%[%s]\"",property);
string=image_info->unique;
break;
}
if (LocaleCompare("units",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)
image->units);
break;
}
if (LocaleCompare("copyright",property) == 0)
break;
}
case 'v':
{
if (LocaleCompare("version",property) == 0)
{
string=GetMagickVersion((size_t *) NULL);
break;
}
break;
}
case 'w':
{
if (LocaleCompare("width",property) == 0)
{
WarnNoImageReturn("\"%%[%s]\"",property);
(void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double)
(image->magick_columns != 0 ? image->magick_columns : 256));
break;
}
break;
}
}
if (string != (char *) NULL)
return(string);
if (*value != '\0')
{
/*
Create a cloned copy of result, that will get cleaned up, eventually.
*/
if (image != (Image *) NULL)
{
(void) SetImageArtifact(image,"get-property",value);
return(GetImageArtifact(image,"get-property"));
}
else
{
(void) SetImageOption(image_info,"get-property",value);
return(GetImageOption(image_info,"get-property"));
}
}
return((char *) NULL);
}
#undef WarnNoImageReturn
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProperty() gets the next free-form string property name.
%
% The format of the GetNextImageProperty method is:
%
% char *GetNextImageProperty(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const char *GetNextImageProperty(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image->filename);
if (image->properties == (void *) NULL)
return((const char *) NULL);
return((const char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->properties));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p r e t I m a g e P r o p e r t i e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretImageProperties() replaces any embedded formatting characters with
% the appropriate image property and returns the interpreted text.
%
% This searches for and replaces
% \n \r \% replaced by newline, return, and percent resp.
% < > & replaced by '<', '>', '&' resp.
% %% replaced by percent
%
% %x %[x] where 'x' is a single letter properity, case sensitive).
% %[type:name] where 'type' a is special and known prefix.
% %[name] where 'name' is a specifically known attribute, calculated
% value, or a per-image property string name, or a per-image
% 'artifact' (as generated from a global option).
% It may contain ':' as long as the prefix is not special.
%
% Single letter % substitutions will only happen if the character before the
% percent is NOT a number. But braced substitutions will always be performed.
% This prevents the typical usage of percent in a interpreted geometry
% argument from being substituted when the percent is a geometry flag.
%
% If 'glob-expresions' ('*' or '?' characters) is used for 'name' it may be
% used as a search pattern to print multiple lines of "name=value\n" pairs of
% the associacted set of properties.
%
% The returned string must be freed using DestoryString() by the caller.
%
% The format of the InterpretImageProperties method is:
%
% char *InterpretImageProperties(ImageInfo *image_info,
% Image *image,const char *embed_text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info. (required)
%
% o image: the image. (optional)
%
% o embed_text: the address of a character string containing the embedded
% formatting characters.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport char *InterpretImageProperties(ImageInfo *image_info,Image *image,
const char *embed_text,ExceptionInfo *exception)
{
#define ExtendInterpretText(string_length) \
DisableMSCWarning(4127) \
{ \
size_t length=(string_length); \
if ((size_t) (q-interpret_text+length+1) >= extent) \
{ \
extent+=length; \
interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \
MaxTextExtent,sizeof(*interpret_text)); \
if (interpret_text == (char *) NULL) \
return((char *) NULL); \
q=interpret_text+strlen(interpret_text); \
} \
} \
RestoreMSCWarning
#define AppendKeyValue2Text(key,value)\
DisableMSCWarning(4127) \
{ \
size_t length=strlen(key)+strlen(value)+2; \
if ((size_t) (q-interpret_text+length+1) >= extent) \
{ \
extent+=length; \
interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \
MaxTextExtent,sizeof(*interpret_text)); \
if (interpret_text == (char *) NULL) \
return((char *) NULL); \
q=interpret_text+strlen(interpret_text); \
} \
q+=FormatLocaleString(q,extent,"%s=%s\n",(key),(value)); \
} \
RestoreMSCWarning
#define AppendString2Text(string) \
DisableMSCWarning(4127) \
{ \
size_t length=strlen((string)); \
if ((size_t) (q-interpret_text+length+1) >= extent) \
{ \
extent+=length; \
interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \
MaxTextExtent,sizeof(*interpret_text)); \
if (interpret_text == (char *) NULL) \
return((char *) NULL); \
q=interpret_text+strlen(interpret_text); \
} \
(void) CopyMagickString(q,(string),extent); \
q+=length; \
} \
RestoreMSCWarning
char
*interpret_text;
MagickBooleanType
number;
register char
*q; /* current position in interpret_text */
register const char
*p; /* position in embed_text string being expanded */
size_t
extent; /* allocated length of interpret_text */
assert(image == NULL || image->signature == MagickCoreSignature);
assert(image_info == NULL || image_info->signature == MagickCoreSignature);
if ((image != (Image *) NULL) && (image->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
else
if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse))
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-image");
if (embed_text == (const char *) NULL)
return(ConstantString(""));
p=embed_text;
while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0'))
p++;
if (*p == '\0')
return(ConstantString(""));
if ((*p == '@') && (IsPathAccessible(p+1) != MagickFalse))
{
/*
Handle a '@' replace string from file.
*/
if (IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,p) == MagickFalse)
{
errno=EPERM;
(void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
"NotAuthorized","`%s'",p);
return(ConstantString(""));
}
interpret_text=FileToString(p+1,~0UL,exception);
if (interpret_text != (char *) NULL)
return(interpret_text);
}
/*
Translate any embedded format characters.
*/
interpret_text=AcquireString(embed_text); /* new string with extra space */
extent=MagickPathExtent; /* allocated space in string */
number=MagickFalse; /* is last char a number? */
for (q=interpret_text; *p!='\0'; number=isdigit(*p) ? MagickTrue : MagickFalse,p++)
{
/*
Look for the various escapes, (and handle other specials)
*/
*q='\0';
ExtendInterpretText(MagickPathExtent);
switch (*p)
{
case '\\':
{
switch (*(p+1))
{
case '\0':
continue;
case 'r': /* convert to RETURN */
{
*q++='\r';
p++;
continue;
}
case 'n': /* convert to NEWLINE */
{
*q++='\n';
p++;
continue;
}
case '\n': /* EOL removal UNIX,MacOSX */
{
p++;
continue;
}
case '\r': /* EOL removal DOS,Windows */
{
p++;
if (*p == '\n') /* return-newline EOL */
p++;
continue;
}
default:
{
p++;
*q++=(*p);
}
}
continue;
}
case '&':
{
if (LocaleNCompare("<",p,4) == 0)
{
*q++='<';
p+=3;
}
else
if (LocaleNCompare(">",p,4) == 0)
{
*q++='>';
p+=3;
}
else
if (LocaleNCompare("&",p,5) == 0)
{
*q++='&';
p+=4;
}
else
*q++=(*p);
continue;
}
case '%':
break; /* continue to next set of handlers */
default:
{
*q++=(*p); /* any thing else is 'as normal' */
continue;
}
}
p++; /* advance beyond the percent */
/*
Doubled Percent - or percent at end of string.
*/
if ((*p == '\0') || (*p == '\'') || (*p == '"'))
p--;
if (*p == '%')
{
*q++='%';
continue;
}
/*
Single letter escapes %c.
*/
if (*p != '[')
{
const char
*string;
if (number != MagickFalse)
{
/*
But only if not preceeded by a number!
*/
*q++='%'; /* do NOT substitute the percent */
p--; /* back up one */
continue;
}
string=GetMagickPropertyLetter(image_info,image,*p, exception);
if (string != (char *) NULL)
{
AppendString2Text(string);
if (image != (Image *) NULL)
(void) DeleteImageArtifact(image,"get-property");
if (image_info != (ImageInfo *) NULL)
(void) DeleteImageOption(image_info,"get-property");
continue;
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"UnknownImageProperty","\"%%%c\"",*p);
continue;
}
{
char
pattern[2*MagickPathExtent];
const char
*key,
*string;
register ssize_t
len;
ssize_t
depth;
/*
Braced Percent Escape %[...].
*/
p++; /* advance p to just inside the opening brace */
depth=1;
if (*p == ']')
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"UnknownImageProperty","\"%%[]\"");
break;
}
for (len=0; len<(MagickPathExtent-1L) && (*p != '\0');)
{
if ((*p == '\\') && (*(p+1) != '\0'))
{
/*
Skip escaped braces within braced pattern.
*/
pattern[len++]=(*p++);
pattern[len++]=(*p++);
continue;
}
if (*p == '[')
depth++;
if (*p == ']')
depth--;
if (depth <= 0)
break;
pattern[len++]=(*p++);
}
pattern[len]='\0';
if (depth != 0)
{
/*
Check for unmatched final ']' for "%[...]".
*/
if (len >= 64)
{
pattern[61] = '.'; /* truncate string for error message */
pattern[62] = '.';
pattern[63] = '.';
pattern[64] = '\0';
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnbalancedBraces","\"%%[%s\"",pattern);
interpret_text=DestroyString(interpret_text);
return((char *) NULL);
}
/*
Special Lookup Prefixes %[prefix:...].
*/
if (LocaleNCompare("fx:",pattern,3) == 0)
{
double
value;
FxInfo
*fx_info;
MagickBooleanType
status;
/*
FX - value calculator.
*/
if (image == (Image *) NULL )
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
fx_info=AcquireFxInfo(image,pattern+3,exception);
status=FxEvaluateChannelExpression(fx_info,IntensityPixelChannel,0,0,
&value,exception);
fx_info=DestroyFxInfo(fx_info);
if (status != MagickFalse)
{
char
result[MagickPathExtent];
(void) FormatLocaleString(result,MagickPathExtent,"%.*g",
GetMagickPrecision(),(double) value);
AppendString2Text(result);
}
continue;
}
if (LocaleNCompare("pixel:",pattern,6) == 0)
{
FxInfo
*fx_info;
double
value;
MagickStatusType
status;
PixelInfo
pixel;
/*
Pixel - color value calculator.
*/
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
GetPixelInfo(image,&pixel);
fx_info=AcquireFxInfo(image,pattern+6,exception);
status=FxEvaluateChannelExpression(fx_info,RedPixelChannel,0,0,
&value,exception);
pixel.red=(double) QuantumRange*value;
status&=FxEvaluateChannelExpression(fx_info,GreenPixelChannel,0,0,
&value,exception);
pixel.green=(double) QuantumRange*value;
status&=FxEvaluateChannelExpression(fx_info,BluePixelChannel,0,0,
&value,exception);
pixel.blue=(double) QuantumRange*value;
if (image->colorspace == CMYKColorspace)
{
status&=FxEvaluateChannelExpression(fx_info,BlackPixelChannel,0,0,
&value,exception);
pixel.black=(double) QuantumRange*value;
}
status&=FxEvaluateChannelExpression(fx_info,AlphaPixelChannel,0,0,
&value,exception);
pixel.alpha=(double) QuantumRange*value;
fx_info=DestroyFxInfo(fx_info);
if (status != MagickFalse)
{
char
name[MagickPathExtent];
(void) QueryColorname(image,&pixel,SVGCompliance,name,
exception);
AppendString2Text(name);
}
continue;
}
if (LocaleNCompare("option:",pattern,7) == 0)
{
/*
Option - direct global option lookup (with globbing).
*/
if (image_info == (ImageInfo *) NULL )
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
if (IsGlob(pattern+7) != MagickFalse)
{
ResetImageOptionIterator(image_info);
while ((key=GetNextImageOption(image_info)) != (const char *) NULL)
if (GlobExpression(key,pattern+7,MagickTrue) != MagickFalse)
{
string=GetImageOption(image_info,key);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? key found but no string value! */
}
continue;
}
string=GetImageOption(image_info,pattern+7);
if (string == (char *) NULL)
goto PropertyLookupFailure; /* no artifact of this specifc name */
AppendString2Text(string);
continue;
}
if (LocaleNCompare("artifact:",pattern,9) == 0)
{
/*
Artifact - direct image artifact lookup (with glob).
*/
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
if (IsGlob(pattern+9) != MagickFalse)
{
ResetImageArtifactIterator(image);
while ((key=GetNextImageArtifact(image)) != (const char *) NULL)
if (GlobExpression(key,pattern+9,MagickTrue) != MagickFalse)
{
string=GetImageArtifact(image,key);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? key found but no string value! */
}
continue;
}
string=GetImageArtifact(image,pattern+9);
if (string == (char *) NULL)
goto PropertyLookupFailure; /* no artifact of this specifc name */
AppendString2Text(string);
continue;
}
if (LocaleNCompare("property:",pattern,9) == 0)
{
/*
Property - direct image property lookup (with glob).
*/
if (image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern);
continue; /* else no image to retrieve artifact */
}
if (IsGlob(pattern+9) != MagickFalse)
{
ResetImagePropertyIterator(image);
while ((key=GetNextImageProperty(image)) != (const char *) NULL)
if (GlobExpression(key,pattern,MagickTrue) != MagickFalse)
{
string=GetImageProperty(image,key,exception);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? */
}
continue;
}
string=GetImageProperty(image,pattern+9,exception);
if (string == (char *) NULL)
goto PropertyLookupFailure; /* no artifact of this specifc name */
AppendString2Text(string);
continue;
}
if (image != (Image *) NULL)
{
/*
Properties without special prefix. This handles attributes,
properties, and profiles such as %[exif:...]. Note the profile
properties may also include a glob expansion pattern.
*/
string=GetImageProperty(image,pattern,exception);
if (string != (const char *) NULL)
{
AppendString2Text(string);
if (image != (Image *) NULL)
(void)DeleteImageArtifact(image,"get-property");
if (image_info != (ImageInfo *) NULL)
(void)DeleteImageOption(image_info,"get-property");
continue;
}
}
if (IsGlob(pattern) != MagickFalse)
{
/*
Handle property 'glob' patterns such as:
%[*] %[user:array_??] %[filename:e*]>
*/
if (image == (Image *) NULL)
continue; /* else no image to retrieve proprty - no list */
ResetImagePropertyIterator(image);
while ((key=GetNextImageProperty(image)) != (const char *) NULL)
if (GlobExpression(key,pattern,MagickTrue) != MagickFalse)
{
string=GetImageProperty(image,key,exception);
if (string != (const char *) NULL)
AppendKeyValue2Text(key,string);
/* else - assertion failure? */
}
continue;
}
/*
Look for a known property or image attribute such as
%[basename] %[denisty] %[delay]. Also handles a braced single
letter: %[b] %[G] %[g].
*/
string=GetMagickProperty(image_info,image,pattern,exception);
if (string != (const char *) NULL)
{
AppendString2Text(string);
continue;
}
/*
Look for a per-image artifact. This includes option lookup
(FUTURE: interpreted according to image).
*/
if (image != (Image *) NULL)
{
string=GetImageArtifact(image,pattern);
if (string != (char *) NULL)
{
AppendString2Text(string);
continue;
}
}
else
if (image_info != (ImageInfo *) NULL)
{
/*
No image, so direct 'option' lookup (no delayed percent escapes).
*/
string=GetImageOption(image_info,pattern);
if (string != (char *) NULL)
{
AppendString2Text(string);
continue;
}
}
PropertyLookupFailure:
/*
Failed to find any match anywhere!
*/
if (len >= 64)
{
pattern[61] = '.'; /* truncate string for error message */
pattern[62] = '.';
pattern[63] = '.';
pattern[64] = '\0';
}
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"UnknownImageProperty","\"%%[%s]\"",pattern);
}
}
*q='\0';
return(interpret_text);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProperty() removes a property from the image and returns its
% value.
%
% In this case the ConstantString() value returned should be freed by the
% caller when finished.
%
% The format of the RemoveImageProperty method is:
%
% char *RemoveImageProperty(Image *image,const char *property)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
*/
MagickExport char *RemoveImageProperty(Image *image,const char *property)
{
char
*value;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
return((char *) NULL);
value=(char *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->properties,
property);
return(value);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P r o p e r t y I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePropertyIterator() resets the image properties iterator. Use it
% in conjunction with GetNextImageProperty() to iterate over all the values
% associated with an image property.
%
% The format of the ResetImagePropertyIterator method is:
%
% ResetImagePropertyIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImagePropertyIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->properties);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o p e r t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProperty() saves the given string value either to specific known
% attribute or to a freeform property string.
%
% Attempting to set a property that is normally calculated will produce
% an exception.
%
% The format of the SetImageProperty method is:
%
% MagickBooleanType SetImageProperty(Image *image,const char *property,
% const char *value,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o property: the image property.
%
% o values: the image property values.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageProperty(Image *image,
const char *property,const char *value,ExceptionInfo *exception)
{
MagickBooleanType
status;
MagickStatusType
flags;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
image->properties=NewSplayTree(CompareSplayTreeString,
RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */
if (value == (const char *) NULL)
return(DeleteImageProperty(image,property)); /* delete if NULL */
status=MagickTrue;
if (strlen(property) <= 1)
{
/*
Do not 'set' single letter properties - read only shorthand.
*/
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
/* FUTURE: binary chars or quotes in key should produce a error */
/* Set attributes with known names or special prefixes
return result is found, or break to set a free form properity
*/
switch (*property)
{
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case '8':
{
if (LocaleNCompare("8bim:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break;
}
#endif
case 'B':
case 'b':
{
if (LocaleCompare("background",property) == 0)
{
(void) QueryColorCompliance(value,AllCompliance,
&image->background_color,exception);
/* check for FUTURE: value exception?? */
/* also add user input to splay tree */
}
break; /* not an attribute, add as a property */
}
case 'C':
case 'c':
{
if (LocaleCompare("channels",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
if (LocaleCompare("colorspace",property) == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,
value);
if (colorspace < 0)
return(MagickFalse); /* FUTURE: value exception?? */
return(SetImageColorspace(image,(ColorspaceType) colorspace,exception));
}
if (LocaleCompare("compose",property) == 0)
{
ssize_t
compose;
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value);
if (compose < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->compose=(CompositeOperator) compose;
return(MagickTrue);
}
if (LocaleCompare("compress",property) == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,MagickFalse,
value);
if (compression < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->compression=(CompressionType) compression;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'D':
case 'd':
{
if (LocaleCompare("delay",property) == 0)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(value,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->delay=(ssize_t)
floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
return(MagickTrue);
}
if (LocaleCompare("delay_units",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
if (LocaleCompare("density",property) == 0)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(value,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
return(MagickTrue);
}
if (LocaleCompare("depth",property) == 0)
{
image->depth=StringToUnsignedLong(value);
return(MagickTrue);
}
if (LocaleCompare("dispose",property) == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value);
if (dispose < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->dispose=(DisposeType) dispose;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case 'E':
case 'e':
{
if (LocaleNCompare("exif:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'F':
case 'f':
{
if (LocaleNCompare("fx:",property,3) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#endif
case 'G':
case 'g':
{
if (LocaleCompare("gamma",property) == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
return(MagickTrue);
}
if (LocaleCompare("gravity",property) == 0)
{
ssize_t
gravity;
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value);
if (gravity < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->gravity=(GravityType) gravity;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'H':
case 'h':
{
if (LocaleCompare("height",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'I':
case 'i':
{
if (LocaleCompare("intensity",property) == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickIntentOptions,MagickFalse,value);
if (intensity < 0)
return(MagickFalse);
image->intensity=(PixelIntensityMethod) intensity;
return(MagickTrue);
}
if (LocaleCompare("intent",property) == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse,
value);
if (rendering_intent < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->rendering_intent=(RenderingIntent) rendering_intent;
return(MagickTrue);
}
if (LocaleCompare("interpolate",property) == 0)
{
ssize_t
interpolate;
interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse,
value);
if (interpolate < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->interpolate=(PixelInterpolateMethod) interpolate;
return(MagickTrue);
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
if (LocaleNCompare("iptc:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
#endif
break; /* not an attribute, add as a property */
}
case 'K':
case 'k':
if (LocaleCompare("kurtosis",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'L':
case 'l':
{
if (LocaleCompare("loop",property) == 0)
{
image->iterations=StringToUnsignedLong(value);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'M':
case 'm':
if ((LocaleCompare("magick",property) == 0) ||
(LocaleCompare("max",property) == 0) ||
(LocaleCompare("mean",property) == 0) ||
(LocaleCompare("min",property) == 0) ||
(LocaleCompare("min",property) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'O':
case 'o':
if (LocaleCompare("opaque",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'P':
case 'p':
{
if (LocaleCompare("page",property) == 0)
{
char
*geometry;
geometry=GetPageGeometry(value);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
return(MagickTrue);
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
if (LocaleNCompare("pixel:",property,6) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
#endif
if (LocaleCompare("profile",property) == 0)
{
ImageInfo
*image_info;
StringInfo
*profile;
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,value,MagickPathExtent);
(void) SetImageInfo(image_info,1,exception);
profile=FileToStringInfo(image_info->filename,~0UL,exception);
if (profile != (StringInfo *) NULL)
status=SetImageProfile(image,image_info->magick,profile,exception);
image_info=DestroyImageInfo(image_info);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'R':
case 'r':
{
if (LocaleCompare("rendering-intent",property) == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse,
value);
if (rendering_intent < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->rendering_intent=(RenderingIntent) rendering_intent;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'S':
case 's':
if ((LocaleCompare("size",property) == 0) ||
(LocaleCompare("skewness",property) == 0) ||
(LocaleCompare("scenes",property) == 0) ||
(LocaleCompare("standard-deviation",property) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'T':
case 't':
{
if (LocaleCompare("tile-offset",property) == 0)
{
char
*geometry;
geometry=GetPageGeometry(value);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'U':
case 'u':
{
if (LocaleCompare("units",property) == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value);
if (units < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->units=(ResolutionType) units;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'V':
case 'v':
{
if (LocaleCompare("version",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'W':
case 'w':
{
if (LocaleCompare("width",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case 'X':
case 'x':
{
if (LocaleNCompare("xmp:",property,4) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#endif
}
/* Default: not an attribute, add as a property */
status=AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(property),ConstantString(value));
/* FUTURE: error if status is bad? */
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5211_0 |
crossvul-cpp_data_bad_1016_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X X W W DDDD %
% X X W W D D %
% X W W D D %
% X X W W W D D %
% X X W W DDDD %
% %
% %
% Read/Write X Windows System Window Dump Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#if defined(MAGICKCORE_X11_DELEGATE)
#include "MagickCore/xwindow-private.h"
#if !defined(vms)
#include <X11/XWDFile.h>
#else
#include "XWDFile.h"
#endif
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_X11_DELEGATE)
static MagickBooleanType
WriteXWDImage(const ImageInfo *,Image *,ExceptionInfo *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s X W D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsXWD() returns MagickTrue if the image format type, identified by the
% magick string, is XWD.
%
% The format of the IsXWD method is:
%
% MagickBooleanType IsXWD(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 IsXWD(const unsigned char *magick,const size_t length)
{
if (length < 8)
return(MagickFalse);
if (memcmp(magick+1,"\000\000",2) == 0)
{
if (memcmp(magick+4,"\007\000\000",3) == 0)
return(MagickTrue);
if (memcmp(magick+5,"\000\000\007",3) == 0)
return(MagickTrue);
}
return(MagickFalse);
}
#if defined(MAGICKCORE_X11_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d X W D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadXWDImage() reads an X Window System window dump 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 ReadXWDImage method is:
%
% Image *ReadXWDImage(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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CheckOverflowException(length,width,height) \
(((height) != 0) && ((length)/((size_t) height) != ((size_t) width)))
char
*comment;
Image
*image;
int
x_status;
MagickBooleanType
authentic_colormap;
MagickStatusType
status;
Quantum
index;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register size_t
pixel;
size_t
length;
ssize_t
count,
y;
unsigned long
lsb_first;
XColor
*colors;
XImage
*ximage;
XWDFileHeader
header;
/*
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 in header information.
*/
count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header);
if (count != sz_XWDheader)
ThrowReaderException(CorruptImageError,"UnableToReadImageHeader");
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
MSBOrderLong((unsigned char *) &header,sz_XWDheader);
/*
Check to see if the dump file is in the proper format.
*/
if (header.file_version != XWD_FILE_VERSION)
ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch");
if (header.header_size < sz_XWDheader)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.visual_class)
{
case StaticGray:
case GrayScale:
{
if (header.bits_per_pixel != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case StaticColor:
case PseudoColor:
{
if ((header.bits_per_pixel < 1) || (header.bits_per_pixel > 15) ||
(header.ncolors == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case TrueColor:
case DirectColor:
{
if ((header.bits_per_pixel != 16) && (header.bits_per_pixel != 24) &&
(header.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.pixmap_format)
{
case XYBitmap:
{
if (header.pixmap_depth != 1)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
break;
}
case XYPixmap:
case ZPixmap:
{
if ((header.pixmap_depth < 1) || (header.pixmap_depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
switch (header.bitmap_pad)
{
case 8:
case 16:
case 32:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.bitmap_unit)
{
case 8:
case 16:
case 32:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.byte_order)
{
case LSBFirst:
case MSBFirst:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
switch (header.bitmap_bit_order)
{
case LSBFirst:
case MSBFirst:
break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (header.ncolors > 65535)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
length=(size_t) (header.header_size-sz_XWDheader);
comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length,(unsigned char *) comment);
comment[length]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/*
Initialize the X image.
*/
ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage));
if (ximage == (XImage *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
ximage->depth=(int) header.pixmap_depth;
ximage->format=(int) header.pixmap_format;
ximage->xoffset=(int) header.xoffset;
ximage->data=(char *) NULL;
ximage->width=(int) header.pixmap_width;
ximage->height=(int) header.pixmap_height;
ximage->bitmap_pad=(int) header.bitmap_pad;
ximage->bytes_per_line=(int) header.bytes_per_line;
ximage->byte_order=(int) header.byte_order;
ximage->bitmap_unit=(int) header.bitmap_unit;
ximage->bitmap_bit_order=(int) header.bitmap_bit_order;
ximage->bits_per_pixel=(int) header.bits_per_pixel;
ximage->red_mask=header.red_mask;
ximage->green_mask=header.green_mask;
ximage->blue_mask=header.blue_mask;
if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) ||
(ximage->format < 0) || (ximage->byte_order < 0) ||
(ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) ||
(ximage->bytes_per_line < 0))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->width > 65535) || (ximage->height > 65535))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32))
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
x_status=XInitImage(ximage);
if (x_status == 0)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
/*
Read colormap.
*/
authentic_colormap=MagickFalse;
colors=(XColor *) NULL;
if (header.ncolors != 0)
{
XWDColor
color;
colors=(XColor *) AcquireQuantumMemory((size_t) header.ncolors,
sizeof(*colors));
if (colors == (XColor *) NULL)
{
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) header.ncolors; i++)
{
count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color);
if (count != sz_XWDColor)
{
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
colors[i].pixel=color.pixel;
colors[i].red=color.red;
colors[i].green=color.green;
colors[i].blue=color.blue;
colors[i].flags=(char) color.flags;
if (color.flags != 0)
authentic_colormap=MagickTrue;
}
/*
Ensure the header byte-order is most-significant byte first.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
for (i=0; i < (ssize_t) header.ncolors; i++)
{
MSBOrderLong((unsigned char *) &colors[i].pixel,
sizeof(colors[i].pixel));
MSBOrderShort((unsigned char *) &colors[i].red,3*
sizeof(colors[i].red));
}
}
/*
Allocate the pixel buffer.
*/
length=(size_t) ximage->bytes_per_line*ximage->height;
if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (ximage->format != ZPixmap)
{
size_t
extent;
extent=length;
length*=ximage->depth;
if (CheckOverflowException(length,extent,ximage->depth))
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data));
if (ximage->data == (char *) NULL)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
count=ReadBlob(image,length,(unsigned char *) ximage->data);
if (count != (ssize_t) length)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
/*
Convert image to MIFF format.
*/
image->columns=(size_t) ximage->width;
image->rows=(size_t) ximage->height;
image->depth=8;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
return(DestroyImageList(image));
}
if ((header.ncolors == 0U) || (ximage->red_mask != 0) ||
(ximage->green_mask != 0) || (ximage->blue_mask != 0))
image->storage_class=DirectClass;
else
image->storage_class=PseudoClass;
image->colors=header.ncolors;
if (image_info->ping == MagickFalse)
switch (image->storage_class)
{
case DirectClass:
default:
{
register size_t
color;
size_t
blue_mask,
blue_shift,
green_mask,
green_shift,
red_mask,
red_shift;
/*
Determine shift and mask for red, green, and blue.
*/
red_mask=ximage->red_mask;
red_shift=0;
while ((red_mask != 0) && ((red_mask & 0x01) == 0))
{
red_mask>>=1;
red_shift++;
}
green_mask=ximage->green_mask;
green_shift=0;
while ((green_mask != 0) && ((green_mask & 0x01) == 0))
{
green_mask>>=1;
green_shift++;
}
blue_mask=ximage->blue_mask;
blue_shift=0;
while ((blue_mask != 0) && ((blue_mask & 0x01) == 0))
{
blue_mask>>=1;
blue_shift++;
}
/*
Convert X image to DirectClass packets.
*/
if ((image->colors != 0) && (authentic_colormap != MagickFalse))
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++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >>
red_shift) & red_mask,exception);
SetPixelRed(image,ScaleShortToQuantum(
colors[(ssize_t) index].red),q);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >>
green_shift) & green_mask,exception);
SetPixelGreen(image,ScaleShortToQuantum(
colors[(ssize_t) index].green),q);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) (pixel >>
blue_shift) & blue_mask,exception);
SetPixelBlue(image,ScaleShortToQuantum(
colors[(ssize_t) index].blue),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
else
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++)
{
pixel=XGetPixel(ximage,(int) x,(int) y);
color=(pixel >> red_shift) & red_mask;
if (red_mask != 0)
color=(color*65535UL)/red_mask;
SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q);
color=(pixel >> green_shift) & green_mask;
if (green_mask != 0)
color=(color*65535UL)/green_mask;
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color),
q);
color=(pixel >> blue_shift) & blue_mask;
if (blue_mask != 0)
color=(color*65535UL)/blue_mask;
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
case PseudoClass:
{
/*
Convert X image to PseudoClass packets.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=(MagickRealType) ScaleShortToQuantum(
colors[i].red);
image->colormap[i].green=(MagickRealType) ScaleShortToQuantum(
colors[i].green);
image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum(
colors[i].blue);
}
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++)
{
index=(Quantum) ConstrainColormapIndex(image,(ssize_t)
XGetPixel(ximage,(int) x,(int) y),exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
break;
}
}
/*
Free image and colormap.
*/
if (header.ncolors != 0)
colors=(XColor *) RelinquishMagickMemory(colors);
ximage->data=DestroyString(ximage->data);
ximage=(XImage *) RelinquishMagickMemory(ximage);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r X W D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterXWDImage() adds properties for the XWD 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 RegisterXWDImage method is:
%
% size_t RegisterXWDImage(void)
%
*/
ModuleExport size_t RegisterXWDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)");
#if defined(MAGICKCORE_X11_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadXWDImage;
entry->encoder=(EncodeImageHandler *) WriteXWDImage;
#endif
entry->magick=(IsImageFormatHandler *) IsXWD;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r X W D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterXWDImage() removes format registrations made by the
% XWD module from the list of supported formats.
%
% The format of the UnregisterXWDImage method is:
%
% UnregisterXWDImage(void)
%
*/
ModuleExport void UnregisterXWDImage(void)
{
(void) UnregisterMagickInfo("XWD");
}
#if defined(MAGICKCORE_X11_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e X W D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteXWDImage() writes an image to a file in X window dump
% rasterfile format.
%
% The format of the WriteXWDImage method is:
%
% MagickBooleanType WriteXWDImage(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 WriteXWDImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*value;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
x;
register unsigned char
*q;
size_t
bits_per_pixel,
bytes_per_line,
length,
scanline_pad;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
XWDFileHeader
xwd_info;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if ((image->columns != (CARD32) image->columns) ||
(image->rows != (CARD32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageType(image,TrueColorType,exception);
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Initialize XWD file header.
*/
(void) memset(&xwd_info,0,sizeof(xwd_info));
xwd_info.header_size=(CARD32) sz_XWDheader;
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
xwd_info.header_size+=(CARD32) strlen(value);
xwd_info.header_size++;
xwd_info.file_version=(CARD32) XWD_FILE_VERSION;
xwd_info.pixmap_format=(CARD32) ZPixmap;
xwd_info.pixmap_depth=(CARD32) (image->storage_class == DirectClass ? 24 : 8);
xwd_info.pixmap_width=(CARD32) image->columns;
xwd_info.pixmap_height=(CARD32) image->rows;
xwd_info.xoffset=(CARD32) 0;
xwd_info.byte_order=(CARD32) MSBFirst;
xwd_info.bitmap_unit=(CARD32) (image->storage_class == DirectClass ? 32 : 8);
xwd_info.bitmap_bit_order=(CARD32) MSBFirst;
xwd_info.bitmap_pad=(CARD32) (image->storage_class == DirectClass ? 32 : 8);
bits_per_pixel=(size_t) (image->storage_class == DirectClass ? 24 : 8);
xwd_info.bits_per_pixel=(CARD32) bits_per_pixel;
bytes_per_line=(CARD32) ((((xwd_info.bits_per_pixel*
xwd_info.pixmap_width)+((xwd_info.bitmap_pad)-1))/
(xwd_info.bitmap_pad))*((xwd_info.bitmap_pad) >> 3));
xwd_info.bytes_per_line=(CARD32) bytes_per_line;
xwd_info.visual_class=(CARD32)
(image->storage_class == DirectClass ? DirectColor : PseudoColor);
xwd_info.red_mask=(CARD32)
(image->storage_class == DirectClass ? 0xff0000 : 0);
xwd_info.green_mask=(CARD32)
(image->storage_class == DirectClass ? 0xff00 : 0);
xwd_info.blue_mask=(CARD32) (image->storage_class == DirectClass ? 0xff : 0);
xwd_info.bits_per_rgb=(CARD32) (image->storage_class == DirectClass ? 24 : 8);
xwd_info.colormap_entries=(CARD32)
(image->storage_class == DirectClass ? 256 : image->colors);
xwd_info.ncolors=(unsigned int)
(image->storage_class == DirectClass ? 0 : image->colors);
xwd_info.window_width=(CARD32) image->columns;
xwd_info.window_height=(CARD32) image->rows;
xwd_info.window_x=0;
xwd_info.window_y=0;
xwd_info.window_bdrwidth=(CARD32) 0;
/*
Write XWD header.
*/
lsb_first=1;
if ((int) (*(char *) &lsb_first) != 0)
MSBOrderLong((unsigned char *) &xwd_info,sizeof(xwd_info));
(void) WriteBlob(image,sz_XWDheader,(unsigned char *) &xwd_info);
if (value != (const char *) NULL)
(void) WriteBlob(image,strlen(value),(unsigned char *) value);
(void) WriteBlob(image,1,(const unsigned char *) "\0");
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
XColor
*colors;
XWDColor
color;
/*
Dump colormap to file.
*/
(void) memset(&color,0,sizeof(color));
colors=(XColor *) AcquireQuantumMemory((size_t) image->colors,
sizeof(*colors));
if (colors == (XColor *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
{
colors[i].pixel=(unsigned long) i;
colors[i].red=ScaleQuantumToShort(ClampToQuantum(
image->colormap[i].red));
colors[i].green=ScaleQuantumToShort(ClampToQuantum(
image->colormap[i].green));
colors[i].blue=ScaleQuantumToShort(ClampToQuantum(
image->colormap[i].blue));
colors[i].flags=(char) (DoRed | DoGreen | DoBlue);
colors[i].pad='\0';
if ((int) (*(char *) &lsb_first) != 0)
{
MSBOrderLong((unsigned char *) &colors[i].pixel,
sizeof(colors[i].pixel));
MSBOrderShort((unsigned char *) &colors[i].red,3*
sizeof(colors[i].red));
}
}
for (i=0; i < (ssize_t) image->colors; i++)
{
color.pixel=(CARD32) colors[i].pixel;
color.red=colors[i].red;
color.green=colors[i].green;
color.blue=colors[i].blue;
color.flags=(CARD8) colors[i].flags;
count=WriteBlob(image,sz_XWDColor,(unsigned char *) &color);
if (count != (ssize_t) sz_XWDColor)
break;
}
colors=(XColor *) RelinquishMagickMemory(colors);
}
/*
Allocate memory for pixels.
*/
length=3*bytes_per_line;
if (image->storage_class == PseudoClass)
length=bytes_per_line;
pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(pixels,0,length);
/*
Convert MIFF to XWD raster pixels.
*/
scanline_pad=(bytes_per_line-((image->columns*bits_per_pixel) >> 3));
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;
if (image->storage_class == PseudoClass)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
for (x=0; x < (ssize_t) scanline_pad; x++)
*q++='\0';
length=(size_t) (q-pixels);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1016_0 |
crossvul-cpp_data_bad_2710_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;
}
if (!ND_TTEST2(*bp, 2)) {
ND_PRINT((ndo, " [|OPT]"));
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:
#define PGM_OPT_LENGTH_LEN (2+2)
if (opt_len != PGM_OPT_LENGTH_LEN) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != %u]",
opt_len, PGM_OPT_LENGTH_LEN));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += 2;
opts_len -= PGM_OPT_LENGTH_LEN;
break;
case PGM_OPT_FRAGMENT:
#define PGM_OPT_FRAGMENT_LEN (2+2+4+4+4)
if (opt_len != PGM_OPT_FRAGMENT_LEN) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != %u]",
opt_len, PGM_OPT_FRAGMENT_LEN));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += 4;
offset = EXTRACT_32BITS(bp);
bp += 4;
len = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= PGM_OPT_FRAGMENT_LEN;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= 4; /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < 4) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, 4);
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += 4;
opt_len -= 4;
opts_len -= 4;
}
break;
case PGM_OPT_JOIN:
#define PGM_OPT_JOIN_LEN (2+2+4)
if (opt_len != PGM_OPT_JOIN_LEN) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != %u]",
opt_len, PGM_OPT_JOIN_LEN));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= PGM_OPT_JOIN_LEN;
break;
case PGM_OPT_NAK_BO_IVL:
#define PGM_OPT_NAK_BO_IVL_LEN (2+2+4+4)
if (opt_len != PGM_OPT_NAK_BO_IVL_LEN) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != %u]",
opt_len, PGM_OPT_NAK_BO_IVL_LEN));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += 4;
seq = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= PGM_OPT_NAK_BO_IVL_LEN;
break;
case PGM_OPT_NAK_BO_RNG:
#define PGM_OPT_NAK_BO_RNG_LEN (2+2+4+4)
if (opt_len != PGM_OPT_NAK_BO_RNG_LEN) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != %u]",
opt_len, PGM_OPT_NAK_BO_RNG_LEN));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += 4;
seq = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= PGM_OPT_NAK_BO_RNG_LEN;
break;
case PGM_OPT_REDIRECT:
#define PGM_OPT_REDIRECT_FIXED_LEN (2+2+2+2)
if (opt_len < PGM_OPT_REDIRECT_FIXED_LEN) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u < %u]",
opt_len, PGM_OPT_REDIRECT_FIXED_LEN));
return;
}
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += 2+2;
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]",
opt_len, PGM_OPT_REDIRECT_FIXED_LEN));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != %u + address size]",
PGM_OPT_REDIRECT_FIXED_LEN, opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= PGM_OPT_REDIRECT_FIXED_LEN + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
#define PGM_OPT_PARITY_PRM_LEN (2+2+4)
if (opt_len != PGM_OPT_PARITY_PRM_LEN) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != %u]",
opt_len, PGM_OPT_PARITY_PRM_LEN));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= PGM_OPT_PARITY_PRM_LEN;
break;
case PGM_OPT_PARITY_GRP:
#define PGM_OPT_PARITY_GRP_LEN (2+2+4)
if (opt_len != PGM_OPT_PARITY_GRP_LEN) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != %u]",
opt_len, PGM_OPT_PARITY_GRP_LEN));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= PGM_OPT_PARITY_GRP_LEN;
break;
case PGM_OPT_CURR_TGSIZE:
#define PGM_OPT_CURR_TGSIZE_LEN (2+2+4)
if (opt_len != PGM_OPT_CURR_TGSIZE_LEN) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != %u]",
opt_len, PGM_OPT_CURR_TGSIZE_LEN));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += 4;
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= PGM_OPT_CURR_TGSIZE_LEN;
break;
case PGM_OPT_NBR_UNREACH:
#define PGM_OPT_NBR_UNREACH_LEN (2+2)
if (opt_len != PGM_OPT_NBR_UNREACH_LEN) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != %u]",
opt_len, PGM_OPT_NBR_UNREACH_LEN));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= PGM_OPT_NBR_UNREACH_LEN;
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:
#define PGM_OPT_SYN_LEN (2+2)
if (opt_len != PGM_OPT_SYN_LEN) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != %u]",
opt_len, PGM_OPT_SYN_LEN));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= PGM_OPT_SYN_LEN;
break;
case PGM_OPT_FIN:
#define PGM_OPT_FIN_LEN (2+2)
if (opt_len != PGM_OPT_FIN_LEN) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != %u]",
opt_len, PGM_OPT_FIN_LEN));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= PGM_OPT_FIN_LEN;
break;
case PGM_OPT_RST:
#define PGM_OPT_RST_LEN (2+2)
if (opt_len != PGM_OPT_RST_LEN) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != %u]",
opt_len, PGM_OPT_RST_LEN));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= PGM_OPT_RST_LEN;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
#define PGM_OPT_CRQST_LEN (2+2)
if (opt_len != PGM_OPT_CRQST_LEN) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != %u]",
opt_len, PGM_OPT_CRQST_LEN));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= PGM_OPT_CRQST_LEN;
break;
case PGM_OPT_PGMCC_DATA:
#define PGM_OPT_PGMCC_DATA_FIXED_LEN (2+2+4+2+2)
if (opt_len < PGM_OPT_PGMCC_DATA_FIXED_LEN) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u < %u]",
opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += 4;
nla_afnum = EXTRACT_16BITS(bp);
bp += 2+2;
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]",
opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != PGM_OPT_PGMCC_DATA_FIXED_LEN + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != %u + address size]",
opt_len, PGM_OPT_PGMCC_DATA_FIXED_LEN));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= PGM_OPT_PGMCC_DATA_FIXED_LEN + 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:
#define PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN (2+2+4+2+2)
if (opt_len < PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN) {
ND_PRINT((ndo, "[Bad PGM_OPT_PGMCC_FEEDBACK option, length %u < %u]",
opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += 4;
nla_afnum = EXTRACT_16BITS(bp);
bp += 2+2;
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]",
opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_FEEDBACK option, length %u != %u + address size]",
opt_len, PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= PGM_OPT_PGMCC_FEEDBACK_FIXED_LEN + 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_2710_0 |
crossvul-cpp_data_bad_3974_0 | /*
* ssh.c
*
* Copyright (C) 2009-2011 by ipoque GmbH
* Copyright (C) 2011-20 - ntop.org
*
* This file is part of nDPI, an open source deep packet inspection
* library based on the OpenDPI and PACE technology by ipoque GmbH
*
* nDPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nDPI 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 nDPI. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ndpi_protocol_ids.h"
#define NDPI_CURRENT_PROTO NDPI_PROTOCOL_SSH
#include "ndpi_api.h"
#include "ndpi_md5.h"
/*
HASSH - https://github.com/salesforce/hassh
https://github.com/salesforce/hassh/blob/master/python/hassh.py
[server]
skex = packet.ssh.kex_algorithms
seastc = packet.ssh.encryption_algorithms_server_to_client
smastc = packet.ssh.mac_algorithms_server_to_client
scastc = packet.ssh.compression_algorithms_server_to_client
hasshs_str = ';'.join([skex, seastc, smastc, scastc])
[client]
ckex = packet.ssh.kex_algorithms
ceacts = packet.ssh.encryption_algorithms_client_to_server
cmacts = packet.ssh.mac_algorithms_client_to_server
ccacts = packet.ssh.compression_algorithms_client_to_server
hassh_str = ';'.join([ckex, ceacts, cmacts, ccacts])
NOTE
THe ECDSA key fingerprint is SHA256 -> ssh.kex.h_sig (wireshark)
is in the Message Code: Diffie-Hellman Key Exchange Reply (31)
that usually is packet 14
*/
/* #define SSH_DEBUG 1 */
static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow);
/* ************************************************************************ */
static int search_ssh_again(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) {
ndpi_search_ssh_tcp(ndpi_struct, flow);
if((flow->protos.ssh.hassh_client[0] != '\0')
&& (flow->protos.ssh.hassh_server[0] != '\0')) {
/* stop extra processing */
flow->extra_packets_func = NULL; /* We're good now */
return(0);
}
/* Possibly more processing */
return(1);
}
/* ************************************************************************ */
static void ndpi_int_ssh_add_connection(struct ndpi_detection_module_struct
*ndpi_struct, struct ndpi_flow_struct *flow) {
if(flow->extra_packets_func != NULL)
return;
flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH;
/* This is necessary to inform the core to call this dissector again */
flow->check_extra_packets = 1;
flow->max_extra_packets_to_check = 12;
flow->extra_packets_func = search_ssh_again;
ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_SSH, NDPI_PROTOCOL_UNKNOWN);
}
/* ************************************************************************ */
static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet,
char *buf, u_int8_t client_hash) {
u_int16_t offset = 22, buf_out_len = 0;
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]);
offset += 4;
/* -1 for ';' */
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
/* ssh.kex_algorithms [C/S] */
strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len);
buf[buf_out_len++] = ';';
offset += len;
/* ssh.server_host_key_algorithms [None] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
offset += 4 + len;
/* ssh.encryption_algorithms_client_to_server [C] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.encryption_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.mac_algorithms_client_to_server [C] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.mac_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
buf[buf_out_len++] = ';';
offset += len;
} else
offset += 4 + len;
/* ssh.compression_algorithms_client_to_server [C] */
if(offset+sizeof(u_int32_t) >= packet->payload_packet_len)
goto invalid_payload;
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
offset += len;
} else
offset += 4 + len;
/* ssh.compression_algorithms_server_to_client [S] */
len = ntohl(*(u_int32_t*)&packet->payload[offset]);
if(!client_hash) {
offset += 4;
if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1))
goto invalid_payload;
strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len);
buf_out_len += len;
offset += len;
} else
offset += 4 + len;
/* ssh.languages_client_to_server [None] */
/* ssh.languages_server_to_client [None] */
#ifdef SSH_DEBUG
printf("[SSH] %s\n", buf);
#endif
return(buf_out_len);
invalid_payload:
#ifdef SSH_DEBUG
printf("[SSH] Invalid packet payload\n");
#endif
return(0);
}
/* ************************************************************************ */
static void ndpi_ssh_zap_cr(char *str, int len) {
len--;
while(len > 0) {
if((str[len] == '\n') || (str[len] == '\r')) {
str[len] = '\0';
len--;
} else
break;
}
}
/* ************************************************************************ */
static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) {
struct ndpi_packet_struct *packet = &flow->packet;
#ifdef SSH_DEBUG
printf("[SSH] %s()\n", __FUNCTION__);
#endif
if(flow->l4.tcp.ssh_stage == 0) {
if(packet->payload_packet_len > 7 && packet->payload_packet_len < 100
&& memcmp(packet->payload, "SSH-", 4) == 0) {
int len = ndpi_min(sizeof(flow->protos.ssh.client_signature)-1, packet->payload_packet_len);
strncpy(flow->protos.ssh.client_signature, (const char *)packet->payload, len);
flow->protos.ssh.client_signature[len] = '\0';
ndpi_ssh_zap_cr(flow->protos.ssh.client_signature, len);
#ifdef SSH_DEBUG
printf("[SSH] [client_signature: %s]\n", flow->protos.ssh.client_signature);
#endif
NDPI_LOG_DBG2(ndpi_struct, "ssh stage 0 passed\n");
flow->l4.tcp.ssh_stage = 1 + packet->packet_direction;
ndpi_int_ssh_add_connection(ndpi_struct, flow);
return;
}
} else if(flow->l4.tcp.ssh_stage == (2 - packet->packet_direction)) {
if(packet->payload_packet_len > 7 && packet->payload_packet_len < 500
&& memcmp(packet->payload, "SSH-", 4) == 0) {
int len = ndpi_min(sizeof(flow->protos.ssh.server_signature)-1, packet->payload_packet_len);
strncpy(flow->protos.ssh.server_signature, (const char *)packet->payload, len);
flow->protos.ssh.server_signature[len] = '\0';
ndpi_ssh_zap_cr(flow->protos.ssh.server_signature, len);
#ifdef SSH_DEBUG
printf("[SSH] [server_signature: %s]\n", flow->protos.ssh.server_signature);
#endif
NDPI_LOG_DBG2(ndpi_struct, "ssh stage 1 passed\n");
flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH;
#ifdef SSH_DEBUG
printf("[SSH] [completed stage: %u]\n", flow->l4.tcp.ssh_stage);
#endif
flow->l4.tcp.ssh_stage = 3;
return;
}
} else if(packet->payload_packet_len > 5) {
u_int8_t msgcode = *(packet->payload + 5);
ndpi_MD5_CTX ctx;
if(msgcode == 20 /* key exchange init */) {
char *hassh_buf = ndpi_calloc(packet->payload_packet_len, sizeof(char));
u_int i, len;
#ifdef SSH_DEBUG
printf("[SSH] [stage: %u][msg: %u][direction: %u][key exchange init]\n", flow->l4.tcp.ssh_stage, msgcode, packet->packet_direction);
#endif
if(hassh_buf) {
if(packet->packet_direction == 0 /* client */) {
u_char fingerprint_client[16];
len = concat_hash_string(packet, hassh_buf, 1 /* client */);
ndpi_MD5Init(&ctx);
ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len);
ndpi_MD5Final(fingerprint_client, &ctx);
#ifdef SSH_DEBUG
{
printf("[SSH] [client][%s][", hassh_buf);
for(i=0; i<16; i++) printf("%02X", fingerprint_client[i]);
printf("]\n");
}
#endif
for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_client[i*2], "%02X", fingerprint_client[i] & 0xFF);
flow->protos.ssh.hassh_client[32] = '\0';
} else {
u_char fingerprint_server[16];
len = concat_hash_string(packet, hassh_buf, 0 /* server */);
ndpi_MD5Init(&ctx);
ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len);
ndpi_MD5Final(fingerprint_server, &ctx);
#ifdef SSH_DEBUG
{
printf("[SSH] [server][%s][", hassh_buf);
for(i=0; i<16; i++) printf("%02X", fingerprint_server[i]);
printf("]\n");
}
#endif
for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_server[i*2], "%02X", fingerprint_server[i] & 0xFF);
flow->protos.ssh.hassh_server[32] = '\0';
}
ndpi_free(hassh_buf);
}
ndpi_int_ssh_add_connection(ndpi_struct, flow);
}
if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) {
#ifdef SSH_DEBUG
printf("[SSH] Dissection completed\n");
#endif
flow->extra_packets_func = NULL; /* We're good now */
}
return;
}
#ifdef SSH_DEBUG
printf("[SSH] Excluding SSH");
#endif
NDPI_LOG_DBG(ndpi_struct, "excluding ssh at stage %d\n", flow->l4.tcp.ssh_stage);
NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_SSH);
}
/* ************************************************************************ */
void init_ssh_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask)
{
ndpi_set_bitmask_protocol_detection("SSH", ndpi_struct, detection_bitmask, *id,
NDPI_PROTOCOL_SSH,
ndpi_search_ssh_tcp,
NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION,
SAVE_DETECTION_BITMASK_AS_UNKNOWN,
ADD_TO_DETECTION_BITMASK);
*id += 1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3974_0 |
crossvul-cpp_data_good_2721_0 | /*
* Copyright (c) 1998-2006 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 Carles Kishimoto <Carles.Kishimoto@bsc.es>
*/
/* \summary: Cisco VLAN Query Protocol (VQP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ether.h"
#define VQP_VERSION 1
#define VQP_EXTRACT_VERSION(x) ((x)&0xFF)
/*
* VQP 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
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Constant | Packet type | Error Code | nitems |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Packet Sequence Number (4 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct vqp_common_header_t {
uint8_t version;
uint8_t msg_type;
uint8_t error_code;
uint8_t nitems;
uint8_t sequence[4];
};
struct vqp_obj_tlv_t {
uint8_t obj_type[4];
uint8_t obj_length[2];
};
#define VQP_OBJ_REQ_JOIN_PORT 0x01
#define VQP_OBJ_RESP_VLAN 0x02
#define VQP_OBJ_REQ_RECONFIRM 0x03
#define VQP_OBJ_RESP_RECONFIRM 0x04
static const struct tok vqp_msg_type_values[] = {
{ VQP_OBJ_REQ_JOIN_PORT, "Request, Join Port"},
{ VQP_OBJ_RESP_VLAN, "Response, VLAN"},
{ VQP_OBJ_REQ_RECONFIRM, "Request, Reconfirm"},
{ VQP_OBJ_RESP_RECONFIRM, "Response, Reconfirm"},
{ 0, NULL}
};
static const struct tok vqp_error_code_values[] = {
{ 0x00, "No error"},
{ 0x03, "Access denied"},
{ 0x04, "Shutdown port"},
{ 0x05, "Wrong VTP domain"},
{ 0, NULL}
};
/* FIXME the heading 0x0c looks ugly - those must be flags etc. */
#define VQP_OBJ_IP_ADDRESS 0x0c01
#define VQP_OBJ_PORT_NAME 0x0c02
#define VQP_OBJ_VLAN_NAME 0x0c03
#define VQP_OBJ_VTP_DOMAIN 0x0c04
#define VQP_OBJ_ETHERNET_PKT 0x0c05
#define VQP_OBJ_MAC_NULL 0x0c06
#define VQP_OBJ_MAC_ADDRESS 0x0c08
static const struct tok vqp_obj_values[] = {
{ VQP_OBJ_IP_ADDRESS, "Client IP Address" },
{ VQP_OBJ_PORT_NAME, "Port Name" },
{ VQP_OBJ_VLAN_NAME, "VLAN Name" },
{ VQP_OBJ_VTP_DOMAIN, "VTP Domain" },
{ VQP_OBJ_ETHERNET_PKT, "Ethernet Packet" },
{ VQP_OBJ_MAC_NULL, "MAC Null" },
{ VQP_OBJ_MAC_ADDRESS, "MAC Address" },
{ 0, NULL}
};
void
vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct vqp_common_header_t *vqp_common_header;
const struct vqp_obj_tlv_t *vqp_obj_tlv;
const u_char *tptr;
uint16_t vqp_obj_len;
uint32_t vqp_obj_type;
u_int tlen;
uint8_t nitems;
tptr=pptr;
tlen = len;
vqp_common_header = (const struct vqp_common_header_t *)pptr;
ND_TCHECK(*vqp_common_header);
if (sizeof(struct vqp_common_header_t) > tlen)
goto trunc;
/*
* Sanity checking of the header.
*/
if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) {
ND_PRINT((ndo, "VQP version %u packet not supported",
VQP_EXTRACT_VERSION(vqp_common_header->version)));
return;
}
/* in non-verbose mode just lets print the basic Message Type */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
nitems = vqp_common_header->nitems;
ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
EXTRACT_32BITS(&vqp_common_header->sequence),
nitems,
len));
/* skip VQP Common header */
tptr+=sizeof(const struct vqp_common_header_t);
tlen-=sizeof(const struct vqp_common_header_t);
while (nitems > 0 && tlen > 0) {
vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr;
ND_TCHECK(*vqp_obj_tlv);
if (sizeof(struct vqp_obj_tlv_t) > tlen)
goto trunc;
vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type);
vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length);
tptr+=sizeof(struct vqp_obj_tlv_t);
tlen-=sizeof(struct vqp_obj_tlv_t);
ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ",
tok2str(vqp_obj_values, "Unknown", vqp_obj_type),
vqp_obj_type, vqp_obj_len));
/* basic sanity check */
if (vqp_obj_type == 0 || vqp_obj_len ==0) {
return;
}
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, vqp_obj_len);
if (vqp_obj_len > tlen)
goto trunc;
switch(vqp_obj_type) {
case VQP_OBJ_IP_ADDRESS:
if (vqp_obj_len != 4)
goto trunc;
ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr)));
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_PORT_NAME:
case VQP_OBJ_VLAN_NAME:
case VQP_OBJ_VTP_DOMAIN:
case VQP_OBJ_ETHERNET_PKT:
safeputs(ndo, tptr, vqp_obj_len);
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_MAC_ADDRESS:
case VQP_OBJ_MAC_NULL:
if (vqp_obj_len != ETHER_ADDR_LEN)
goto trunc;
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr)));
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len);
break;
}
tptr += vqp_obj_len;
tlen -= vqp_obj_len;
nitems--;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|VQP]"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2721_0 |
crossvul-cpp_data_good_5237_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
if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0)
|| (tga->bits == TGA_BPP_32 && tga->alphabits == 8)))
{
gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n",
tga->bits, tga->alphabits);
return -1;
}
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;
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 ] & !TGA_RLE_FLAG ) + 1 );
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size);
bitmap_caret += pixel_block_size;
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size);
bitmap_caret += (encoded_pixels * pixel_block_size);
buffer_caret += (encoded_pixels * 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/good_5237_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.